\chapter{工具包的基础概念}
\thispagestyle{empty}

\section{Class Categories and Domains【类的功能】}

\subsection{What is a class category?【什么是功能模块?】}
In the design of a large software system such as GEANT4, it is
essential to partition it into smaller logical units. This makes the design well
organized and easier to develop. Once the logical units are defined independent
to each other as much as possible, they can be developed in parallel without
serious interference.

在设计一个像 Geant4
这样的大型软件系统时，有必要把它分为一些小的逻辑单元，这将使整个设计过程容易组织。定义不同的逻辑单元之间尽量相互独立（松耦合），使它们可以并行的开发而没有过多的相互影响。
In object-oriented analysis and design methodology by Grady Booch
\textit{[Booch1994]}, class categories are used to create logical units. They are defined as ``clusters of classes that are themselves cohesive,
but are loosely coupled relative to other clusters.''
This means that a class category contains classes which have a close
 relationship (for example, the ``has-a'' relation).
However, relationships between classes which belong to different
class categories are weak, i.e., only limited classes of these have ``uses'' relations.
The class categories and their relations are presented by a class category diagram.
The class category diagram designed for GEANT4 is shown in the figure
below (Fig. \ref{fig:3.1}). Each box in the figure represents a class category, and a ``uses'' relation by a straight line.
The circle at an end of a straight line means the class category which has this circle uses the other category.


Grady Booch 在《Object-Oriented Analysis and Design with Applications 》提到，不同模块用于建立不同的逻辑单元，它的定义是"它是一组相互紧耦合的类，但是与其他组之间的关系是松耦合的。 " 这意味着一个模块的类包含了那些相互之间有着紧密关系的类，它们与属于其他模块的类之间的关系是弱的，只有一些有限数量的类之间有“使用”关系。功能模块与它们之间的关系用一个模块关系图来表示。下面是 Geant4 中不同功能模块之间的关系图，每个框，表示一个模块，直线表示使用关系，在直线终端的圆，表示该功能模块使用了其他模块中的类。

The file organization of the GEANT4 codes follows basically the
structure of this class category. This \textit{User's Manual }is also organized according to class categories.

Geant4 代码文件的组织关系，基本上是遵循模块之间的关系结构。本 手册也是按照这种结构组织的。

In the development and maintenance of GEANT4, one software team
will be assigned to a class category. This team will have a responsibility to
develop and maintain all classes belonging to the class category.

在 Geant4 工具包的开发维护过程中，一个软件小组将接手一个模块的所有类的开发和维护

任务。


\begin{figure}[htbp]
\centering
\label{fig:3.1}
\includegraphics[width=0.8\textwidth]{FIG/fig3-1.png}
\caption{Class categories in GEANT4.}
\end{figure}


\subsection{Class categories in GEANT4【在 Genat4 中的功能模块】}

The following is a brief summary of the role of each class category in
GEANT4.

下面概述了 Geant4 中各个模块的角色。

\begin{enumerate}
	\item Run and Event


These are categories related to the generation of events, interfaces to event
generators, and any secondary particles produced. Their roles are principally to
provide particles to be tracked to the Tracking Management.


	\item Tracking and Track
	
	These are categories related to propagating a particle by analyzing the factors
limiting the step and applying the relevant physics processes. The important
aspect of the design was that a generalized GEANT4 physics
process (or interaction) could perform actions, along a tracking step, either
localized in space, or in time, or distributed in space and time (and all the
possible combinations that could be built from these cases).

\item Geometry and Magnetic Field

These categories manage the geometrical definition of a detector (solid
modeling) and the computation of distances to solids (also in a magnetic field).
The GEANT4 geometry solid modeler is based on the ISO STEP
standard and it is fully compliant with it. A key feature of the GEANT4 geometry is that the volume definitions are independent of the solid
representation. By this abstract interface for the G4 solids, the tracking
component works identically for various representations. The treatment of the
propagation in the presence of fields

has been provided within specified accuracy. An OO design allows to exchange
different numerical algorithms and/or different fields (not only B-field),
without affecting any other component of the toolkit.

\item Particle Definition and Matter

These two categories manage the the definition of materials and particles.

\item Physics

This category manages all physics processes participating in the interactions of
particles in matter. The abstract interface of physics processes allows multiple
implementations of physics models per interaction or per channel. Models can be
selected by energy range, particle type, material, etc. Data encapsulation and
polymorphism make it possible to give transparent access to the cross sections
(independently of the choice of reading from an ascii file, or of interpolating
from a tabulated set, or of computing analytically from a formula).
Electromagnetic and hadronic physics were handled in a uniform way in such a
design, opening up the physics to the users.

\item Hits and Digitization

These two categories manage the creation of hits and their use for the
digitization phase. The basic design and implementation of the Hits and Digi had
been realized, and also several prototypes, test cases and scenarios had been
developed before the alpha-release. Volumes (not necessarily the ones used by the
tracking) are aggregated in sensitive detectors, while hits collections represent
the logical read out of the detector. Different ways of creating and managing
hits collections had been delivered and tested, notably for both single hits and
calorimetry hits types. In all cases, hits collections had been successfully
stored into and retrieved from an Object Data Base Management System.

\item Visualization

This manages the visualization of solids, trajectories and hits, and interacts
with underlying graphical libraries (the Visualization class category). The basic
and most frequently used graphics functionality had been implemented already by
the alpha-release. The OO design of the visualization component allowed us to
develop several drivers independently, such as for OpenGL, Qt and OpenInventor
(for X11 and Windows), DAWN, Postscript (via DAWN) and VRML.


\item Interfaces

This category handles the production of the graphical user interface (GUI) and
the interactions with external software (OODBMS, reconstruction etc.).

\end{enumerate}



\begin{enumerate}

\item Run 和事件（run、 event）

这些模块的类与事件产生、事件发生器接口，和次级粒子产生有关，它们原则上向粒子跟踪管理类提供被跟踪的粒子。

\item  粒子跟踪和径迹 （tracking、 track）

这些模块的类与粒子的输运过程有关，这是 Geant4 的一个重要部分。它使得 Geant4应用程序的物理过程可以模拟各种行为， 在粒子跟踪的每一步，
记录粒子的空间位置，或者时间，或者随空间和时间的分布（和所有这些可能的组合）。

\item 几何体，磁场，和 CAD 接口 （geometry）

这三个模块的任务是管理探测器的几何定义（实体建模及与 CAD 系统的交互）和实体之间的距离（包括在磁场中）。 Geant4 的几何实体建模是基于 ISO
STEP [7]标准的，并且与它完全兼容，这保证了 Geant4 能够和 CAD 系统交换几何信息。 Geant4 几何的一个关键特性是独立与实体描述，通过那些
G4 实体的抽象接口，使得不同的几何描述，对于粒子跟踪部分来说都是一致的。对于在场中的输运过程， Geant4
已经指定了模拟过程的精度。但是，面向对象的设计使得用户可以替换不同的算法和不同的场，而不影响工具包中的其他部分。

\item  粒子和介质的定义 （particle、 material）

有两个模块是用来管理粒子和材料的定义的。

\item 物理（physics）

这个模块管理所有与介质发生作用的物理过程。物理接口的抽象接口允许对每个反应通道和每个作用过程实现多个物理模型， 这些物理模型可以通过能量范围、
粒子类型、介质材料等，来进行选择。面向对象的数据封装和多态的特性使得截面数据的存取过程是透明的（与截面数据的数据源无关）。正是这些特性，使得用户可以使用同样的方式来处理电磁作用过程和强作用过程。

\item  Hits 和数字化（hits 、 digitization）

有两个模块用来管理 hits 的构建，以及它在数字化部分的使用。 Hits
和数字化的基本设计和实现已经完成，并且在$\alpha{}$版发行前就提供了几个原型和测试情况。在灵敏感探测器的几何体中， hits collections
表示探测器的逻辑输出。我们已经测试并发布了创建和管理 hits collections 的不同方法,特别是 single hits 和量热器 hits
这两种类型。在任何情况下，已经可以成功地将 hits collections 保存到对像数据管理系统（Object DataBase Management
System），也可以从里面读取相应数据。

\item 可视化（Visualization ）

这是用来管理实体、径迹和 hits
的可视化，以及与底层图形库的交互。那些基本的、频繁使用的图形功能已经在$\alpha{}$版的时候实现。面向对象的设计允许我们开发独立的不同的可视化引擎，
例如基于 OpenGL 或者 OpenInventor (对于 X11 与 Windows 环境),DAWN, Postscript (使用 DAWN)或者
VRML 的不同引擎。

\item  接口（Interfaces）

这个模块处理 GUI 的输出和与外部软件(OODBMS 等)的交互。
\end{enumerate}



\section{Global Usage Classes【全局类】}

The ``global'' category in GEANT4 collects all classes, types,
structures and constants which are considered of general use within the
GEANT4 toolkit. This category also defines the interface with
third-party software libraries (CLHEP, STL, etc.) and system-related types, by
defining, where appropriate, typedefs according to the GEANT4
code conventions.

在"global"这个模块中，包含了那些在 Geant4
工具包中最通用的类，数据类型，结构，和常量，同时，它还定义了与第三方软件库的接口，及与系统相关的类型的转换。

\subsection{Signature of GEANT4 classes【Geant4 类的命名】}

In order to keep an homogeneous naming style, and according to the
GEANT4 coding style conventions, each class part of the
GEANT4 kernel has its name beginning with the prefix G4, e.g.,
G4VHit, G4GeometryManager, G4ProcessVector, etc. Instead of the raw C types, G4
types are used within the GEANT4 code. For the basic numeric
types (int, float, double, etc.), different compilers and different platforms
provide different value ranges. In order to assure portability, the use of G4int,
G4float, G4double, G4bool, globally defined, is preferable. G4 types implement
the right generic type for a given architecture.

为了使用统一的命名方式，遵循 Geant4 的一些约定， Geant4 内核的每一个类的名字都以前缀 G4 开头。例如， G4VHit,
G4GeometryManager, G4ProcessVector, 等。为了便于移植，在Geant4 中使用 G4 类型（G4int, G4float,
G4double， 等）代替 C 中原有的类型(int, float,double, 等)。因为这些基本类型，在不同的编译器和平台中有不同的定义， G4
类型实现了不同给定环境的通用类型。

\paragraph{Basic types【基本类型】}
The basic types in GEANT4 are considered to be the following:\newline
 在Geant4 中的基本类型：

\begin{itemize}
	\item G4int,
	\item G4long,
	\item G4float,
	\item G4double,
	\item G4bool,
	\item G4complex,
	\item G4String.
\end{itemize}

which currently consist of simple typedefs to respective types defined in the
CLHEP, STL or system libraries. Most definitions of these basic types come with
the inclusion of a single header file, globals.hh. This file also provides
inclusion of required system headers, as well as some global utility functions
needed and used within the GEANT4 kernel.

通常由简单的 typedef 和各自在 CLHEP, STL 或者系统库中的类型定义组成。多数基本类型的定义包含了头文件
globals.hh，这个头文件中包含了那些系统头文件和在 Geant4 内核中需要并使用了的全局实用函数。

\paragraph{Typedefs to CLHEP classes and their usage【CLHEP 类在 Geant4中的类型定义及它们的使用方法】}

The following classes are typedefs to the corresponding classes of the CLHEP(Computing Library for High Energy Physics) distribution. For more detailed documentation please refer to the
\href{http://cern.ch/clhep/manual/RefGuide/}{CLHEP reference guide} and the \href{http://cern.ch/clhep/manual/UserGuide/}{CLHEP usermanual}.

下面的这些类是基于 CLHEP (Computing Library for High Energy Physics)
中的相应类定义的。有关的详细文档请参阅《\href{http://cern.ch/clhep/manual/RefGuide/}{CLHEP
reference
guide}》和《\href{http://cern.ch/clhep/manual/UserGuide/}{CLHEP
user manual}》。

\begin{itemize}
	\item G4ThreeVector, G4RotationMatrix, G4LorentzVector and G4LorentzRotation:


Vector classes: defining 3-component (x,y,z) vector entities, rotation of such
objects as 3x3 matrices, 4component (x,y,z,t) vector entities and their rotation
as 4x4 matrices.


	\item G4Plane3D, G4Transform3D, G4Normal3D, G4Point3D, G4Scale3D, and G4Vector3D:


Geometrical classes: defining geometrical entities and transformations in 3D
space.
\end{itemize}
\vspace{1cm}
\begin{itemize}
\item G4ThreeVector, G4RotationMatrix, G4LorentzVector 和
G4LorentzRotation

向量类：定义了 3 元向量，和它的 3$\times{}$3 旋转变换矩阵， 4 元向量，和对应的 4$\times{}$4 旋转变换矩阵。

\item  G4Plane3D, G4Transform3D, G4Normal3D, G4Point3D, 和 G4Vector3D

几何类：定义了几何实体和它们在 3D 空间中的变换。
\end{itemize}


\subsection{The \textit{HEPRandom }module in CLHEP【CLHEP 中的 HEPRandom 模块】}

The \textit{HEPRandom }module, originally part of the GEANT4
kernel, and now distributed as a module of CLHEP, has been designed and developed
starting from the \textit{Random }class of MC++, the original CLHEP's
\textit{HepRandom }module and the Rogue Wave approach in the Math.h++ package.
For detailed documentation on the \textit{HEPRandom }classes see the
\href{http://cern.ch/clhep/manual/RefGuide/}{CLHEP reference guide} and the
\href{http://cern.ch/clhep/manual/UserGuide/}{CLHEP user
manual}.

Information written in this manual is extracted from the original
\href{http://cern.ch/clhep/manual/UserGuide/Random/Random.html}{manifesto}
distributed with the \textit{HEPRandom }package.

The \textit{HEPRandom }module consists of classes implementing different random
engines and different random distributions. A distribution associated to an
engine constitutes a random generator. A distribution class can collect different
algorithms and different calling sequences for each method to define distribution
parameters or range-intervals. An engine implements the basic algorithm for
pseudo-random numbers generation.

There are 3 different ways of shooting random values:

\vspace{1cm}

HEPRandom 模块原本就是 Geant4 内核的一个部分，目前作为 CLHEP 的一个模块发行。最初的 CLHEP's HepRandom 模块和
Math.h++ 中的 Rogue Wave【Rouge Wave 是 RougeWave 公司提供的 STL】的基础上进行开发的。有关 HEPRandom
类的详细情况，请参看《\href{http://cern.ch/clhep/manual/RefGuide/}{CLHEP reference guide} 》或《\href{http://cern.ch/clhep/manual/UserGuide/}{CLHEP user
manual}》。

本手册中所提到的有关信息是从与 HEPRandom 一起发行的原始文档中摘录的。

HEPRandom
模块由实现不同随机引擎和不同随机分布的类组成的。一个随机分布和一个随机引擎组成一个随机数发生器。一个随机分布类可以通过不同的算法，和不同的调用顺序，来定义不同的分布参数和区间。其中一个随机引擎实现了伪随机数发生器的基本算法。

产生随机数的 3 种不同方式：

\begin{enumerate}
	\item Using the static generator defined in the \textit{HepRandom }class: random
values are shot using static methods shoot() defined for each distribution class.
The static generator will use, as default engine, a \textit{MixMaxRng }object,
and the user can set its properties or change it with a new instantiated engine
object by using the static methods defined in the \textit{HepRandom }class.
	\item Skipping the static generator and specifying an engine object: random values are
shot using static methods shoot(*HepRandomEngine) defined for each distribution
class. The user must instantiate an engine object and give it as argument to the
shoot method. The generator mechanism will then be by-passed by using the basic
flat() method of the specified engine. The user must take care of the engine
objects he/she instantiates.
	\item Skipping the static generator and instantiating a distribution object: random
values are shot using fire() methods (NOT static) defined for each distribution
class. The user must instantiate a distribution object giving as argument to the
constructor an engine by pointer or by reference. By doing so, the engine will be
associated to the distribution object and the generator mechanism will be
by-passed by using the basic flat() method of that engine.
\end{enumerate}

\vspace{1cm}
\begin{enumerate}

\item 使用在 HepRandom 类中定义的静态随机数发生器：随机数是由不同随机分布类中定义的静态方法 shoot() 产生的。静态随机数发生器将使用一个
HepJamesRandom 对象作为缺省引擎，用户可以使用在 HepRandom 类中定义的静态方法来实例化一个新的引擎，从而设置或者改变随机数发射器的属性。

\item 指定一个随机引擎：使用不同随机分布的类中定义的静态方法shoot(*HepRandomEngine) 产生随机数。用户必须向 shoot
方法传递一个随机引擎的对象。通过调用指定随机引擎的 flat() 方法可以旁路相应的随机数发生机制。用户必须注意他所实例化的随机引擎。

\item 实例化一个随机分布：随机数由不同随机分布类中定义的 fire() 方法 methods
(非静态方法)产生。用户必须通过指针或者应用向随机数发生器的构造函数传递一个随机分布对象，使随机分布与随机引擎相关联。可以使用相应随机引擎的 flat()
方法来旁路特定的随机数发生机制。
\end{enumerate}


In this guide, we'll only focus on the static generator (point 1.), since the
static interface of \textit{HEPRandom }is the only one used within the
GEANT4 toolkit.

由于在 Geant4 工具包中只使用了 HEPRandom 的静态接口，所以，在本手册中，我们只关心静态发生器。

\paragraph{\textit{HEPRandom }engines【HEPRandom 随机引擎】}

The class \textit{HepRandomEngine }is the abstract class defining the interface
for each random engine. It implements the getSeed() and getSeeds() methods which
return the initial seed value and the initial array of seeds (if any)
respectively. Many concrete random engines can be defined and added to the
structure, simply making them inheriting from \textit{HepRandomEngine}. Several
different engines are currently implemented in \textit{HepRandom}, we describe
here five of them:

HepRandomEngine 类是一个抽象类，它为每个随机引擎定义了一个接口。它实现了getSeed() 和 getSeeds()
方法，这两个方法分别返回``初始随机种子''和``初始随机种子数组'' （如果存在）。用户可以从 HepRandomEngine派生具体的随机引擎，并添加到
HepRandom中。目前，在 HepRandom 中，已经实现了几个不同的随机引擎 。下面是其中的 5 个：

\begin{itemize}
	\item \textit{HepJamesRandom}


It implements the algorithm described in \textit{F.James, Comp. Phys. Comm. 60
(1990) 329 }for pseudo-random number generation.


	\item \textit{DRand48Engine}


Random engine using the drand48() and srand48() system functions from C standard
library to implement the flat() basic distribution and for setting seeds
respectively. \textit{DRand48Engine }uses the seed48() function from C standard
library to retrieve the current internal status of the generator, which is
represented by 3 short values. \textit{DRand48Engine }is the only engine defined
in \textit{HEPRandom }which intrinsically works in 32 bits precision. Copies of
an object of this kind are not allowed.


	\item \textit{MixMaxRng}


Random number engine implementing the MixMax Matrix Generator of Pseudorandom
Numbers generator proposed by \textit{N.Z.Akopov, G.K.Saviddy and
N.G.Ter-Arutyunian, J.Compt.Phy. 97, (1991) 573 }and \textit{G.Savvidy and
N.Savvidy, J.Comput.Phys. 97 (1991) 566}. This is the default random engine for
the static generator; it will be invoked by each distribution class unless the
user sets a different one.


	\item \textit{RanluxEngine}


The algorithm for \textit{RanluxEngine }has been taken from the original
implementation in FORTRAN77 by Fred James, part of the MATHLIB HEP library. The
initialisation is carried out using a Multiplicative Congruential generator using
formula constants of L'Ecuyer as described in \textit{F.James, Comp. Phys. Comm.
60 (1990) 329344}. The engine provides five different luxury levels for quality
of random generation. When instantiating a \textit{RanluxEngine}, the user can
specify the luxury level to the constructor (if not, the default value 3 is
taken). For example:
\begin{lstlisting}
RanluxEngine theRanluxEngine(seed,4);
// instantiates an engine with `seed' and the best luxury-level
... or
RanluxEngine theRanluxEngine;
// instantiates an engine with default seed value and luxury-level
...
\end{lstlisting}

The class provides a getLuxury() method to get the engine luxury level.

The SetSeed() and SetSeeds() methods to set the initial seeds for the engine,
can be invoked specifying the luxury level. For example:
\begin{lstlisting}
// static interface
HepRandom::setTheSeed(seed,4);
HepRandom::setTheSeed(seed);
// sets the seed to `seed' and luxury to 4
// sets the seed to `seed' keeping
// the current luxury level
\end{lstlisting}
\item \textit{RanecuEngine}

The algorithm for \textit{RanecuEngine }is taken from the one originally written
in FORTRAN77 as part of the MATHLIB HEP library. The initialisation is carried
out using a Multiplicative Congruential generator using formula constants of
L'Ecuyer as described in \textit{F.James, Comp. Phys. Comm. 60 (1990) 329-344}.
Handling of seeds for this engine is slightly different than the other engines in
\textit{HEPRandom}. Seeds are taken from a seed table given an index, the
getSeed() method returns the current index of seed table. The setSeeds() method
will set seeds in the local SeedTable at a given position index (if the index
number specified exceeds the table's size, [index\%size] is taken). For example:
\begin{lstlisting}
// static interface
const G4long* table_entry;
table_entry = HepRandom::getTheSeeds();
// it returns a pointer `table_entry' to the local SeedTable
// at the current `index' position. The couple of seeds
// accessed represents the current `status' of the engine itself !
...
G4int index=n;
G4long seeds[2];
HepRandom::setTheSeeds(seeds,index);
// sets the new `index' for seeds and modify the values inside
// the local SeedTable at the `index' position. If the index
// is not specified, the current index in the table is considered.
...
\end{lstlisting}

The setSeed() method resets the current `status' of the engine to the original
seeds stored in the static table of seeds in \textit{HepRandom}, at the specified
index.


\end{itemize}


\begin{itemize}
\item HepJamesRandom

它实现了在``F.James, Comp. Phys. Comm. 60 (1990)
329''中描述的伪随机数发生的算法。这是静态随机数发生器的缺省随机引擎；如果用户不设置其他的引擎，它将被每个随机分布类所调用。

\item DRand48Engine

使用 C 标准库中的系统函数 drand48() 和 srand48()来实现基本的 flat() 分布和设置随机种子。 DRand48Engine 使用 C
标准库中的系统函数 seed48() 来获得随机数发生器的内部状态（3 个 short 型值）， DRand48Engine 是在 HEPRandom
中定义的唯一的随机引擎，它实际工作在 32 位的精度。这个类型的对象复制是不允许的。

\item RandEngine

它是一个简单的随机引擎，使用 C 标准库中的 rand() 和 srand() 来实现基本分布flat() 和设置随机种子。请注意
rand()产生的随机数的谱分布特性，如果要产生一个 高质量的、或者是长周期的随机数，我们不推荐使用这个随机引擎。这个类型的对象复制是不允许的。

\item RanluxEngine

RanluxEngine 的算法是从最初在 MATHLIB HEP 中，由 Fred James 用
FORTRAN77实现的版本移植过来的。它通过使用一个乘同余法的随机数发生器进行初始化，该发生器使用了在``F.James, Comp. Phys. Comm.
60 (1990) 329-344''中提到的 L'Ecuyer 常数。这个随机引擎提供了 5 个不同级别质量的随机数，在实例化 RanluxEngine
的时候，用户向构造函数可以指定质量级别（缺省是 3）。例如：
\begin{lstlisting}
RanluxEngine theRanluxEngine(seed,4);
// instantiates an engine with `seed' and the best luxury-level
... or
RanluxEngine theRanluxEngine;
// instantiates an engine with default seed value and luxury-level
...
\end{lstlisting}


这个类提供了一个 getLuxury() 方法来查询随机引擎的质量级别。

SetSeed() 和 SetSeeds() 方法用于设置随机种子，它们也可以用来指定质量级别。例如
\begin{lstlisting}
// static interface
HepRandom::setTheSeed(seed,4);
HepRandom::setTheSeed(seed);
// sets the seed to `seed' and luxury to 4
// sets the seed to `seed' keeping
// the current luxury level
\end{lstlisting}


\item RanecuEngine

RanecuEngine 的算法使用了在 MATHLIB HEP 库中用 FORTRAN77
编写的版本。它通过使用一个乘同余法的随机数发生器进行初始化，该发生器使用了在``F.James,Comp. Phys. Comm. 60 (1990)
329-344''中提到的 L'Ecuyer 常数。这个引擎的随机种子处理与同在 HEPRandom 中的其他引擎略有不同，
它通过一个给定索引号从一个随机种子表中取得随机种子，它的 getSeed() 方法同样返回的是随机种子的当前索引号。通过给定当前 SeedTable
的索引号，使用 setSeeds()方法设置随机种子（如果索引号超过随机种子表的长度，将使用 [index\%size] 的余数)。例如：

\begin{lstlisting}
// static interface
const G4long* table_entry;
table_entry = HepRandom::getTheSeeds();
// it returns a pointer `table_entry' to the local SeedTable
// at the current `index' position. The couple of seeds
// accessed represents the current `status' of the engine itself !
...
G4int index=n;
G4long seeds[2];
HepRandom::setTheSeeds(seeds,index);
// sets the new `index' for seeds and modify the values inside
// the local SeedTable at the `index' position. If the index
// is not specified, the current index in the table is considered.
...
\end{lstlisting}


setSeed() 方法复位随机引擎的当前状态，使用 HepRandom 的静态随机种子表中给定位置的随机种子。
\end{itemize}

Except for the \textit{RanecuEngine}, for which the internal status is
represented by just a couple of longs, all the other engines have a much more
complex representation of their internal status, which currently can be obtained
only through the methods saveStatus(), restoreStatus() and showStatus(), which
can also be statically called from \textit{HepRandom}. The status of the
generator is needed for example to be able to reproduce a run or an event in a
run at a given stage of the simulation.

\textit{RanecuEngine }is probably the most suitable engine for this kind of
operation, since its internal status can be fetched/reset by simply using
getSeeds()/setSeeds() (getTheSeeds()/setTheSeeds() for the static interface in
\textit{HepRandom}).


除了 RanecuEngine 的内部状态是由一对 long 型值外，其余引擎都有一些更加复杂的状态。目前，这些状态只能通过方法 saveStatus(),
restoreStatus() 和 showStatus()来实现，它们可以从 HepRandom 中静态的调用。如果用户需要在一个给定的模拟状态下，重新产生一个
run 或在 run 中的一个事件， 那么这些随机数发生器的内部状态是必须的。

RanecuEngine 可能是用于实现这种操作的最佳引擎，它的内部状态可以通过方法getSeeds()/setSeeds() (对与在 HepRandom
中静态接口是 getTheSeeds()/setTheSeeds())非常容易的存取/复位。

\paragraph{The static interface in the \textit{HepRandom }class【HepRandom
类中的静态接口】}

\textit{HepRandom }a singleton class and using a \textit{MixMaxRng }engine as
default algorithm for pseudo-random number generation. \textit{HepRandom }defines
a static private data member, theGenerator, and a set of static methods to
manipulate it. By means of theGenerator, the user can change the underlying
engine algorithm, get and set the seeds, and use any kind of defined random
distribution. The static methods setTheSeed() and getTheSeed() will set and get
respectively the initial seed to the main engine used by the static generator.
For example:

HepRandom 是一个 singleton 类【Singleton
类，有的书上译作单实例类，其实例称为单例，指该类只能有一个实例，且在类声明的时候就自动初始化了】，它使用 HepJamesRandom
引擎作为伪随机数发生的缺省算法。 HepRandom 定义了一个私有静态数据成员，theGenerator 和一系列用于操作该成员的静态方法。通过
theGenerator,用户可以更改当前随机引擎算法，存取随机种子，使用各种定义的随机分布。静态方法 setTheSeed() 和getTheSeed()
分别用于设置和获取静态随机数发生器所使用的随机引擎的初始化种子。例如

\begin{lstlisting}
HepRandom::setTheSeed(seed); // to change the current seed to 'seed'
int startSeed = HepRandom::getTheSeed(); // to get the current initial seed
HepRandom::saveEngineStatus();
// to save the current engine status on file
HepRandom::restoreEngineStatus(); // to restore the current engine to a previous
// saved configuration
HepRandom::showEngineStatus();
// to display the current engine status to stdout
...
int index=n;
long seeds[2];
HepRandom::getTheTableSeeds(seeds,index);
// fills `seeds' with the values stored in the global
// seedTable at position `index'
\end{lstlisting}

Only one random engine can be active at a time, the user can decide at any time
to change it, define a new one (if not done already) and set it. For example:

用户在同一时刻只能使用一个随机引擎，但可以在任何时刻进行更改所使用的随机引擎，或者定义一个新的随机引擎（如果尚未定义）并设置它为当前使用的随机引擎。例如：

\begin{lstlisting}
RanecuEngine theNewEngine;
HepRandom::setTheEngine(&theNewEngine);
...
\end{lstlisting}

or simply setting it to an old instantiated engine (the old engine status is
kept and the new random sequence will start exactly from the last one previously
interrupted). For example:

或者简单的将一个已经经过初始化的引擎(该引擎的运行状态已被保存，新的随机数序列将从原先中断的地方开始)设为当前随机引擎。例如：

\begin{lstlisting}
HepRandom::setTheEngine(&myOldEngine);
\end{lstlisting}


Other static methods defined in this class are:\\
其它在该类中定义的静态方法如下：

\begin{itemize}
	\item void setTheSeeds(const G4long* seeds, G4int)
	\item const G4long* getTheSeeds()
	
	To set/get an array of seeds for the generator, in the case of a
\textit{RanecuEngine }this corresponds also to set/get the current status of the
engine.

设置/获取随机数发生器的随机种子数组，对于 RanecuEngine 引擎来说，它们同时还设置/获取该随机引擎的当前状态。

\item HepRandomEngine* getTheEngine()

To get a pointer to the current engine used by the static generator.
获取指向当前使用的随机引擎的指针。
\end{itemize}

\paragraph{\textit{HEPRandom }distributions【HEPRandom 随机分布】}

A distribution-class can collect different algorithms and different calling
sequences for each method to define distribution parameters or range-intervals;
it also collects methods to fill arrays, of specified size, of random values,
according to the distribution. This class collects either static and not static
methods. A set of distribution classes are defined in \textit{HEPRandom}. Here is
the description of some of them:

一个随机分布类包括了不同的随机算法，和每个算法的不同调用顺序，用来定义不同的随机分布参数和取值区间；对应不同的分布，它还包含那些用于填充指定长度的随机数组的不同方法。在
HEPRandom 中定义了一系列的随机分布类，如下：

\begin{itemize}
	\item \textit{RandFlat }Class to shoot flat random values (integers or double) within
a specified interval. The class provides also methods to shoot just random bits.
	\item \textit{RandExponential }Class to shoot exponential distributed random values,
given a mean (default mean = 1)
	\item \textit{RandGauss }Class to shoot Gaussian distributed random values, given a
mean (default = 0) or specifying also a deviation (default = 1). Gaussian random
numbers are generated two at the time, so every other time a number is shot, the
number returned is the one generated the time before.
	\item \textit{RandBreitWigner }Class to shoot numbers according to the Breit-Wigner
distribution algorithms (plain or mean\textasciicircum{}2).
	\item \textit{RandPoisson }Class to shoot numbers according to the Poisson
distribution, given a mean (default = 1) (Algorithm taken from W.H.Press et al.,
\textit{Numerical Recipes in C}, Second Edition).
\end{itemize}

\vspace{1cm}
\begin{itemize}
\item RandFlat

用于产生指定区间内均匀分布的随机数（整型或双精度），该类同时提供了用于产生随机位序列（bits）的方法。

\item  RandExponential

用于产生给定平均值，指数分布的随机数（缺省平均值为 1）。

\item  RandGauss

用于产生给定平均值（缺省为 0），或者指定偏差（缺省为
1），高斯（Gauss）分布的随机数。因为每次产生两个高斯分布的随机数，所以，下一次返回的值同样也是本次产生的。

\item  RandBreitWigner

用于产生符合 Breit-Wigner 分布算法的随机数 (均匀分布 或者 mean\textasciicircum{}2)。

\item  RandPoisson

用于产生给定平均值（缺省为 1），符合泊松（Poisson）分布的随机数(算法取自``W.H.Press et al., Numerical Recipes
in C, Second Edition'').

\end{itemize}

\subsection{The \textit{HEPNumerics }module【HEPNumerics 模块】}

A set of classes implementing numerical algorithms has been developed in
GEANT4. Most of the algorithms and methods have been implemented
mainly based on recommendations given in the books:

在 Geant4 中已经实现了一系列的数值算法类。这些算法和方法主要是居于以下书中所推荐的方法实现的：

\begin{itemize}
	\item B.H. Flowers, \textit{An introduction to Numerical Methods In C++}, Clarendon
Press, Oxford 1995.
	\item M. Abramowitz, I. Stegun, \textit{Handbook of mathematical functions}, DOVER
Publications INC, New York 1965 ; chapters 9, 10, and 22.
\end{itemize}

This set of classes includes: 这些类包括：

\begin{itemize}
	\item G4ChebyshevApproximation Class creating the Chebyshev approximation for a
function pointed by fFunction data member. The Chebyshev polynomial approximation
provides an efficient evaluation of the minimax polynomial, which (among all
polynomials of the same degree) has the smallest maximum deviation from the true
function.
	\item G4DataInterpolation Class providing methods for data interpolations and
extrapolations: Polynomial, Cubic Spline, . . .
	\item G4GaussChebyshevQ
	\item G4GaussHermiteQ
	\item G4GaussJacobiQ
	\item G4GaussLaguerreQ Classes implementing the Gauss-Chebyshev, Gauss-Hermite,
Gauss-Jacobi, GaussLaguerre and Gauss-Legendre quadrature methods. Roots of
orthogonal polynomials and corresponding weights are calculated based on
iteration method (by bisection Newton algorithm).
	\item G4Integrator Template class collecting integrator methods for generic functions
(Legendre, Simpson, Adaptive Gauss, Laguerre, Hermite, Jacobi).
	\item G4SimpleIntegration Class implementing simple numerical methods (Trapezoidal,
MidPoint, Gauss, Simpson, Adaptive Gauss, for integration of functions with
signature: double f(double).
\end{itemize}

\begin{itemize}
\item G4ChebyshevApproximation

该类为数据成员 fFunction
所指的函数创建了一个车比雪夫(Chebyshev)近似多项式，这个多项式提供了一个评价最小极大值多项式的有效方法。最小极大值多项式是指在所有同阶多项式中，它与原函数相比，有最小的最大偏差。

\item  G4DataInterpolation

该类提供了数据内插和外推的方法：多项式， 三次样条， \ldots{}..

\item  G4GaussChebyshevQ

\item G4GaussHermiteQ

\item G4GaussJacobiQ

\item  G4GaussLaguerreQ

这些类实现了高斯－车比雪夫，高斯－埃尔米特（Hermite），高斯－雅各比（Jacobi），高斯－拉格朗日（Laguerre），高斯－勒让德（Legendre）求积分方法。正交多项式的根与对应的权是通过迭代算法（二分法）计算的。

\item  G4Integrator

该类是一个模板类， 包括了一些通用函数(勒让德， 幸普森（Simpson）， Adaptive Gauss，勒让德， Hermite，雅各比)的积分方法。

\item  G4SimpleIntegration

该类实现了简单的数值积分方法(梯形、中值、高斯、幸普森、 Adaptive Gauss)。

\end{itemize}


\subsection{General management classes【通用管理类】}

The global category defines also a set of utility classes generally used within
the kernel of GEANT4. These classes include:

`global' 类同时定义了一系列的实用类，它们用于 Geant4 内核。这些类包括：

\begin{itemize}
\item G4Allocator

A class for fast allocation of objects to the heap through paging mechanism.
It's meant to be used by associating it to the object to be allocated and
defining for it new and delete operators via MallocSingle() and FreeSingle()
methods of G4Allocator.

该类通过页机制快速的为对象从堆中申请空间。它有两个方法 MallocSingle()和FreeSingle()分别对应于 new 和 delete 操作符。

\rule{\textwidth}{1 pt}
\begin{flushleft}
Note: G4Allocator assumes that objects being allocated have all the same size
for the type they represent. For this reason, classes which are handled by
G4Allocator should \textit{avoid }to be used as base-classes for others.
Similarly, base-classes of sub-classes handled through G4Allocator should not
define their (eventually empty) virtual destructors inlined; such measure is
necessary in order also to prevent bad aliasing optimisations by compilers which
may potentially lead to crashes in the attempt to free allocated chunks of memory
when using the base-class pointer or not.

注意：G4Allocator假定被分配的对象与它们表示的类具有完全相同的大小。 出于这个原因，由G4Allocator处理的类应该避免被用作其他类的基类。
同样，通过G4Allocator处理的子类的基类不应该定义内联的（最终是空的）虚拟析构函数;
这样的措施对于防止编译器的错误混叠优化是必要的，这可能会导致在使用基类指针时尝试释放分配的内存块时崩溃。
\end{flushleft}
\rule{\textwidth}{1 pt}
\end{itemize}


The list of allocators implicitly defined and used in GEANT4 is
reported here:

这里报告了在GEANT4中隐含定义和使用的分配器列表：

\begin{itemize}
	\item events (G4Event): anEventAllocator
	\item tracks (G4Track): aTrackAllocator
	\item stacked tracks (G4StackedTrack): aStackedTrackAllocator
	\item primary particles (G4PrimaryParticle): aPrimaryParticleAllocator
	\item primary vertices (G4PrimaryVertex): aPrimaryVertexAllocator
	\item decay products (G4DecayProducts): aDecayProductsAllocator
	\item digits collections of an event (G4DCofThisEvent): anDCoTHAllocator
	\item digits collections (G4DigiCollection): aDCAllocator
	\item hits collections of an event (G4HCofThisEvent): anHCoTHAllocator
	\item hits collections (G4HitsCollection): anHCAllocator
	\item touchable histories (G4TouchableHistory): aTouchableHistoryAllocator
	\item trajectories (G4Trajectory): aTrajectoryAllocator
	\item trajectory points (G4TrajectoryPoint): aTrajectoryPointAllocator
	\item trajectory containers (G4TrajectoryContainer): aTrajectoryContainerAllocator
	\item navigation levels (G4NavigationLevel): aNavigationLevelAllocator
	\item navigation level nodes (G4NavigationLevelRep): aNavigLevelRepAllocator
	\item reference-counted handles (G4ReferenceCountedHandle$<$X$>$): aRCHAllocator
	\item counted objects (G4CountedObject$<$X$>$): aCountedObjectAllocator
	\item HEPEvt primary particles (G4HEPEvtParticle): aHEPEvtParticleAllocator
	\item electron occupancy objects(G4ElectronOccupancy): aElectronOccupancyAllocator
	\item ``rich'' trajectories (G4RichTrajectory): aRichTrajectoryAllocator
	\item ``rich'' trajectory points (G4RichTrajectoryPoint):
aRichTrajectoryPointAllocator
	\item ``smooth'' trajectories (G4SmoothTrajectory): aSmoothTrajectoryAllocator
	\item ``smooth'' trajectory points (G4SmoothTrajectoryPoint):
aSmoothTrajectoryPointAllocator
	\item ``ray'' trajectories (G4RayTrajectory): G4RayTrajectoryAllocator
	\item ``ray'' trajectory points (G4RayTrajectoryPoint): G4RayTrajectoryPointAllocator
\end{itemize}

For each of these allocators, accessible from the global namespace, it is
possible to monitor the allocation in their memory pools or force them to release
the allocated memory (for example at the end of a run):

对于可从全局名称空间访问的这些分配器中的每一个，都可以监视其内存池中的分配，或强制它们释放分配的内存（例如在运行结束时）：

\begin{lstlisting}
// Return the size of the total memory allocated for tracks
//
aTrackAllocator.GetAllocatedSize();
// Return allocated storage for tracks to the free store
//
aTrackAllocator.ResetStorage();
\end{lstlisting}

\begin{itemize}
	\item G4ReferenceCountedHandle


Template class acting as a smart pointer and wrapping the type to be counted. It
performs the reference counting during the life-time of the counted object.

	\item G4FastVector
	
	Defines a physics vector which has values of energy-loss, cross-section, and
other physics values of a particle in matter in a given range of the energy,
momentum, etc. This class serves as the base class for a vector having various
energy scale, for example like `log' (G4PhysicsLogVector) `linear'
(G4PhysicsLinearVector), `free' (G4PhysicsFreeVector), etc.

	\item G4LPhysicsFreeVector
	
	mplements a free vector for low energy physics cross-section data. A
subdivision method is used to find the energy$\vert{}$momentum bin.

\item G4PhysicsOrderedFreeVector

A physics ordered free vector inherits from G4PhysicsVector. It provides, in
addition, a method for the user to insert energy/value pairs in sequence. Methods
to retrieve the max and min energies and values from the vector are also
provided.

\item G4Timer

Utility class providing methods to measure elapsed user/system process time.
Uses $<$sys/times.h$>$ and $<$unistd.h$>$ - POSIX.1.

\item G4UserLimits

Class collecting methods for get and set any kind of step limitation allowed in
GEANT4.

\item G4UnitsTable

Placeholder for the system of units in GEANT4.

\end{itemize}

\begin{itemize}
\item G4ReferenceCountedHandle该类是一个模板类，它就像是一个用于计数的指针，记录对象在生命周期内被应用的次数。

\item G4FastVector

该类是一个模板类，定义了一个指针向量，且并不进行边界检查。

\item G4PhysicsVector

该类定义了一个物理向量，它包括在给定能量、动量等范围条件下，一个粒子在物质中的能量损失，反应截面和其他物理量。它作为其他物理向量类的基类，如，
'log'(G4PhysicsLogVector) 'linear' (G4PhysicsLinearVector),
'free'(G4PhysicsFreeVector), 等。

\item G4LPhysicsFreeVector

该类实现了用于低能物理反应截面数据的自由向量类，提供了用于查找 能量$\vert{}$动量窗的方法。

\item  G4PhysicsOrderedFreeVector

该类是从 G4PhysicsVector 派生的，实现了物理有序的自由向量类，同时提供了顺序插入 能量/数值
对的方法，并且也提供了从该向量中取得最大、最小能量和数值的方法。

\item G4Timer

该实用类提供了用于测量 用户/系统 进程所消耗时间的方法。使用了 $<$sys/times.h$>$ 和 $<$unistd.h$>$ - POSIX.1.规范

\item G4UserLimits

该类提供了各种方法，用于在 Geant4 中获取和设置各种限制条件。

\item G4UnitsTable

该类实现了在 Geant4 中所使用的单位系统的占位符。

\end{itemize}

\section{System of units【单位系统】}

\subsection{Basic units【基本单位】}

GEANT4 offers the user the possibility to choose and use the
preferred units for any quantity. In fact, GEANT4 takes care of
the units. Internally a consistent set on units based on the HepSystemOfUnits is
used:

Geant4 向用户提供了使用他们可能喜欢的单位。事实上， Geant4 内核在内部使用一个统一的单位集合，它是基于 HepSystemOfUnits 的：
%\begin{multicols}{2}

\begin{table}
\centering
\begin{tabular}{p{5cm}p{5cm}}
millimeter                                          &                         (mm) \\
nanosecond           &                           (ns)\\
Mega electron Volt  &   (MeV)\\
positron charge  &    (eplus)\\
degree Kelvin&(kelvin)\\
the amount of substance&(mole)\\
luminous intensity&(candela)\\
radian&(radian)\\
steradian&(steradian)\\
\end{tabular}
\end{table}

%\end{multicols}

All other units are defined from the basic ones. 所有其他的单位都是有这些基本单位导出的。

For instance:

\begin{lstlisting}
millimeter = mm = 1;
meter = m = 1000*mm;
...
m3 = m*m*m;
...
\end{lstlisting}

In the file \$CLHEP\_BASE\_DIR/include/CLHEP/Units/SystemOfUnits.h from the
CLHEP installation, one can find all units definitions.

One can also change the system of units to be used by the kernel.

在文件 source/global/management/include/SystemOfUnits.h 中，可以找到这些定义，这个文件是 CLHEP
的一部分。

此外，用户可以自由的改变内核所使用的单位系统。

\subsection{Input your data【输入数据】}

\paragraph{Avoid `hard coded' data【避免使用 'hard coded' 数据】}

The user must give the units for the data to introduce: 你必须对你所引入的数据指定单位

\begin{lstlisting}
G4double Size = 15*km, KineticEnergy = 90.3*GeV, density = 11*mg/cm3;
\end{lstlisting}

GEANT4 assumes that these specifications for the units are
respected, in order to assure independence from the units chosen in the client
application.

If units are not specified in the client application, data are implicitly
treated in internal GEANT4 system units; this practice is however
strongly discouraged.

If the data set comes from an array or from an external file, it is strongly
recommended to set the units as soon as the data are read, before any treatment.
For instance:

事实上，所有的 Geant4 代码都是遵循这些规范，这使得代码与用户选择的单位系统无关。

如果单位没有指定，这些数据将被认为使用 G4 系统内部的隐含单位，我们反对这样的做法，那样用户在写代码的时候必须清楚 G4
系统的隐含单位，这使得代码的移植性变差。

如果数据集来自于一个数组或外部文件，我们强烈推荐在读取数据的时候设置它们的单位。例如：

\begin{lstlisting}
for (int j=0, j<jmax, j++) CrossSection[j] *= millibarn;
...
my calculations
...
\end{lstlisting}

\paragraph{Interactive commands【交互式命令】}

Some built-in commands from the User Interface (UI) also require units to be
specified. For instance:

一些用户接口的内建命令也要求指定单位。例如：

\begin{lstlisting}
/gun/energy 15.2 keV
/gun/position 3 2 -7 meter
\end{lstlisting}

If units are not specified, or are not valid, the command is refused.

如果不指定这些单位，或者指定的单位无效，那么系统将拒绝执行这些命令。

\subsection{Output your data【输出数据】}

You can output your data with the wished units. To do so, it is sufficient to
divide the data by the corresponding unit:

用户可以使用他喜欢的单位输出数据，只要将这些数据除以相应的单位:

\begin{lstlisting}
G4cout << KineticEnergy/keV << " keV";
G4cout << density/(g/cm3)<< " g/cm3";
\end{lstlisting}

Of course, G4cout $<$$<$ KineticEnergy will print the energy in the internal
units system.

There is another way to output the data. Let GEANT4 choose the
most appropriate units for the actual numerical value of the data. It is
sufficient to specify to which category the data belong to (Length, Time, Energy,
etc.). For example:

当然， G4cout $<$$<$ KineticEnergy 将输出使用系统内部单位的能量值。

用户也可以让 Geant4 来选择使用最合适的单位来输出数据，只要指定用户数据的类别（属于 Length, Time, Energy, 等）。例如:
\begin{lstlisting}
G4cout << G4BestUnit(StepSize, "Length");
\end{lstlisting}

StepSize will be printed in km, m, mm, fermi, etc. depending of its actual
value.

StepSize 将根据实际的数据输出相应的单位， km, m, mm, fermi, 等。

\subsection{Introduce new units【引入新的单位】}

If wished to introduce new units, there are two methods: 如果用户希望引入新的单位，有两个方法：

\begin{itemize}
	\item You can extend the file SystemOfUnits.h在头文件 SystemOfUnits.h 中添加新的单位
	
	\begin{lstlisting}
#include "SystemOfUnits.h"
static const G4double inch = 2.54*cm;
\end{lstlisting}

Using this method, it is not easy to define composed units. It is better to do
the following:

使用这个方法定义复合单位有些困难，最好使用下面的方法：

\item Instantiate an object of the class G4UnitDefinition. These objects are owned by the global G4UnitsTable at construction, and must not be deleted by the user.
用户可以实例化一个 G4UnitDefinition 类的对象
\begin{lstlisting}
new G4UnitDefinition ( name, symbol, category, value )
\end{lstlisting}

For example: define a few units for speed例：定义一些速度单位

\begin{lstlisting}
new G4UnitDefinition ( "km/hour" , "km/h", "Speed", km/(3600*s) );
new G4UnitDefinition ( "meter/ns", "m/ns", "Speed", m/ns );
\end{lstlisting}

The category ``Speed'' does not exist by default in G4UnitsTable, but it will be
created automatically. The class G4UnitDefinition is defined in
source/global/management/G4UnitsTable.hh.

在 G4UnitsTable 中， "Speed" 类的单位缺省不存在，但是它将自动被建立。G4UnitDefinition 类位于
source/global/management 目录下。
\end{itemize}

\subsection{Print the list of units【输出单位列表】}

You can print the list of units with the static function:
G4UnitDefinition::PrintUnitsTable(); or with the interactive command: /units/list

用户可以使用静态函数 G4UnitDefinition::PrintUnitsTable()输出单位列表，或者使用交互式命令， /units/list 。

\section{Run}

\subsection{Basic concept of \textit{Run【Run 的基本概念】}}

In GEANT4, \textit{Run }is the largest unit of simulation. A run
consists of a sequence of events. Within a run, the detector geometry, the set up
of sensitive detectors, and the physics processes used in the simulation should
be kept unchanged. A run is represented by a G4Run class object. A run starts
with BeamOn() method of G4RunManager.

在 Geant4 中， Run 是一个最大的模拟单位，一个 run 由一系列的事件组成，它是 G4Run 的一个对象，由 G4RunManager 的方法
beamOn()启动。在一个 run 过程中，探测器几何，灵敏探测器设置，和模拟中所使用的物理过程，都保持不变。

\paragraph{Representation of a run【与 run 有关的表述】}

G4Run represents a run. It has a run identification number, which should be set
by the user, and the number of events simulated during the run. Please note that
the run identification number is not used by the GEANT4 kernel,
and thus can be arbitrarily assigned at the user's convenience.

G4Run 代表一个 run，它有一个 run 的标识数和在这 run 中所要模拟的事件数。这个标识数可以由用户任意设置，因为在 Geant4
内核中并未用到这个标识。

G4Run has pointers to the tables G4VHitsCollection and G4VDigiCollection. These
tables are associated in case \textit{sensitive detectors }and \textit{digitizer
modules }are simulated, respectively. The usage of these tables will be mentioned
in \textit{Hits }and \textit{Digitization}.

G4Run 有两个指向 G4VHitsCollection 和 G4VDigiCollection 表的指针。这两个表，分别与sensitive
detectors 和 digitizer modules 模拟相关，它们的使用将在\textit{Hits}
和\textit{Digitization}中讨论。

G4Run has two virtual methods, and thus you can extend G4Run class. In
particular if you use GEANT4 in multithreaded mode and need to
accumulate values, these two virtual method must be overwritten to specify how
such values should be collected firstly for a worker thread, and then for the
entire run. These virtual methods are the following.

G4Run有两种虚拟方法，因此可以扩展G4Run类。
特别是如果您在多线程模式下使用GEANT4并需要累加值，则必须覆盖这两个虚拟方法，以指定首先应该如何为工作线程收集这些值，然后再针对整个运行收集这些值。
这些虚拟方法如下。

\textbf{virtual void RecordEvent(const G4Event*) }Method to be overwritten by
the user for recording events in this (thread-local) run. At the end of the
implementation, G4Run base-class method for must be invoked for recording data
members in the base class.

\textbf{void Merge(const G4Run*) }Method to be overwritten by the user for
merging local Run object to the global Run object. At the end of the
implementation, G4Run base-class method for must be invoked for merging data
members in the base class.

virtual void RecordEvent（const G4Event *）方法被用户覆盖以便在此（线程本地）运行中记录事件。
在实现结束时，必须调用G4Run基类方法来记录基类中的数据成员。

void Merge（const G4Run *）方法被用户覆盖以将本地Run对象合并到全局Run对象。
在实现结束时，必须调用G4Run基类方法来合并基类中的数据成员。

\paragraph{Manage the run procedures【管理 run 的进程】}

G4RunManager manages the procedures of a run. In the constructor of
G4RunManager, all of the manager classes in GEANT4 kernel, except
for some static managers, are constructed. These managers are deleted in the
destructor of G4RunManager. G4RunManager must be a singleton created in the
user's main() program; the pointer to this singleton object can be obtained by
other code using the GetRunManager() static method.

G4RunManager 管理一个 run 的相关进程。在 G4RunManager 的构造函数中，除一些静态管理类外，其余所有的管理类都被构造，这些类将被
G4RunManager 的析构函数删除。G4RunManager 必须是一个 singleton 对象,用户可以通过静态方法 getRunManager()
获取指向这个 singleton 对象的指针。

As already mentioned in \textit{How to Define the main() Program}, all of the
\textit{user initialization }classes defined by the user should be assigned to
G4RunManager before starting initialization of the GEANT4 kernel.
The assignments of these user classes are done by SetUserInitialization()
methods. All user classes defined by the GEANT4 kernel will be
summarized in \textit{User Actions}.

正如在 2.1 节中提到的，通过使用方法 SetUserInitialization()和
SetUserAction()，将用户定义的用户初始化类和用户行为类在 Geant4 内核初始化前传递给 G4RunManager 。Geant4
内核定义的所有用户类将在第 6 章中概述。

G4RunManager has several public methods, which are listed below.

G4RunManager 有几个公用方法：
\begin{itemize}
\item \textbf{Initialize() }

All initializations required by the GEANT4
kernel are triggered by this method. Initializations are:
\begin{itemize}
\item construction of the detector geometry and set up of sensitive detectors and/or digitizer modules,
\item construction of particles and physics processes,
\item calculation of cross-section tables.
\end{itemize}

This method is thus mandatory before proceeding to the first run. This method
will be invoked automatically for the second and later runs in case some of the
initialized quantities need to be updated.

\item \textbf{BeamOn(G4int numberOfEvent) }

This method triggers the actual simulation
of a run, that is, an event loop. It takes an integer argument which represents
the number of events to be simulated.

\item \textbf{GetRunManager() }

This static method returns the pointer to the
G4RunManager singleton object.

\item \textbf{GetCurrentEvent() }

This method returns the pointer to the G4Event object
which is currently being simulated. This method is available only when an event
is being processed. At this moment, the application state of GEANT4, which is explained in the following sub-section, is ``EventProc''. When
GEANT4 is in a state other than ``EventProc'', this method
returns null. Please note that the return value of this method is const G4Event *
and thus you cannot modify the contents of the object.

\item  \textbf{SetNumberOfEventsToBeStored(G4int nPrevious) }

When simulating the ``pile
up'' of more than one event, it is essential to access more than one event at the
same moment. By invoking this method, G4RunManager keeps nPrevious G4Event
objects. This method must be invoked before proceeding to BeamOn().

\item \textbf{GetPreviousEvent(G4int i\_thPrevious) }

The pointer to the i\_thPrevious
G4Event object can be obtained through this method. A pointer to a const object
is returned. It is inevitable that i\_thPrevious events must have already been
simulated in the same run for getting the i\_thPrevious event. Otherwise, this
method returns null.

\item \textbf{AbortRun() }

This method should be invoked whenever the processing of a
run must be stopped. It is valid for GeomClosed and EventProc states. Run
processing will be safely aborted even in the midst of processing an event.
However, the last event of the aborted run will be incomplete and should not be
used for further analysis.
\end{itemize}

\vspace{1cm}

\begin{itemize}
\item initialize()

Geant4 内核必须的所有初始化都是由这个方法触发的。这些初始化如下：
\begin{itemize}
\item 探测器几何、灵敏探测器或数字化模块设置的构成 ，
\item 粒子和物理过程的构成，
\item 反应截面表的计算。
\end{itemize}


这个方法必须在第一个 run 执行之前调用。对于第二个 run 和以后的 run，如果某些初始化参数需要改变，那么，它将自动被调用。

\item beamOn(G4int numberOfEvent)

这个方法触发一个实际的模拟过程，即一个事件循环。它有一个整型参数，表示被模拟的事件数。

\item getRunManager()这个静态方法返回指向 G4RunManager singleton 对象的指针。

\item getCurrentEvent()

这个方法返回指向当前模拟的 G4Event 对象的指针，它只有在事件模拟过程中是可用的，在这个时候， Geant4 应用程序的状态是"EventProc"。如果
Geant4 的状态不是"EventProc"，这个方法将返回一个空指针。注意返回值的类型是 const G4Event *，因此用户不能更改对象的内容。有关
Geant4 应用程序的状态将在下一小节讨论。

\item setNumberOfEventsToBeStored(G4int nPrevious)

对于模拟多个事件``堆积''的情况，实际就是在同一时刻同时存取多个事件。通过调用这个方法， G4RunManager 将保存 nPrevious 个
G4Event 对象。这个方法必须在beamOn()执行之前调用。

\item getPreviousEvent(G4int i\_thPrevious)

通过这个方法，用户可以获取指向 i\_thPrevious G4Event 对象的指针，返回值是一个指向 const 型对象的指针。在获取
i\_thPrevious 事件指针之前，必须有在同一次 run中的 i\_thPrevious 个事件已经被模拟，否则，将返回空指针。

\item abortRun()

这个方法可以在需要中止一个 run
模拟过程的时候调用，它将安全的中止模拟过程，即使是在一个事件模拟的中间过程。但是，用户需要注意，这个被中止的最后一个事件模拟是不完全的， 不可以用来做更多的分析。
这个方法在 GeomClosed 和 EventProc这两个状态下是可用的。
\end{itemize}

\paragraph{Run manager classes for multi-threading mode}

G4MTRunManager is the replacement of G4RunManager for multi-threading mode. At
the very end of Initialize() method, G4MTRunManager creates and starts worker
threads. The event each thread is tasked is in first-come-first-served basis, so
that event numbers each thread has are not sequential.

G4WorkerRunManager is the local RunManager automatically instantiated by
G4MTRunManager to take care of initialization and event handling of a thread.
Both G4MTRunManager and G4WorkerRunManager are derived classes of G4RunManager
base class.

The static method G4RunManager::GetRunManager() returns the following pointer.

\begin{itemize}
	\item It returns the pointer to the G4WorkerRunManager of the local thread when it is
invoked from thread-local object.
	\item It returns the pointer to the G4MTRunManager when it is invoked from shared
object.
	\item It returns the pointer to the base G4RunManager if it is used in the sequential
mode.
\end{itemize}

G4RunManager has a method GetRunManagerType() that returns an enum named RMType
to indicate what kind of RunManager it is. RMType is defined as \{ sequentialRM,
masterRM, workerRM \}. From the thread-local object, a static method
G4MTRunManager::GetMasterRunManager() is available to access to G4MTRunManager.
From a worker thread, the user may access to, for example, detector construction
(it is a shared class) through this GetMasterRunManager() method.

\paragraph{G4UserRunAction}

G4UserRunAction is one of the \textit{user action }classes from which you can
derive your own concrete class. This base class has three virtual methods as
follows:

G4UserRunAction 是一个用户行为类，从它可以派生用户自己的类。这个基类，有两个虚拟方法：

\begin{itemize}
\item \textbf{GenerateRun() }
This method is invoked at the beginning of the BeamOn()
method but after confirmation of the conditions of the GEANT4
kernel. This method should be used to instantiate a user-specific run class
object.
\item \textbf{BeginOfRunAction() }
This method is invoked at the beginning of the
BeamOn() method but after confirmation of the conditions of the GEANT4 kernel. Likely uses of this method include:

\begin{itemize}
	\item setting a run identification number,
	\item booking histograms,
	\item setting run specific conditions of the sensitive detectors and/or digitizer
modules (e.g., dead channels).
\end{itemize}
\item \textbf{EndOfRunAction() }
This method is invoked at the very end of the BeamOn()
method. Typical use cases of this method are

\begin{itemize}
	\item store/print histograms,
	\item manipulate run summaries.
\end{itemize}

\end{itemize}

\begin{itemize}
\item GenerateRun（）

在BeamOn（）方法开始时调用此方法，除非是确认GEANT4内核的条件才是在之后调用此方法。 应该使用此方法来实例化用户特定的运行类对象。

\item beginOfRunAction()

这个方法在 beamOn() 方法开始的时候被调用。可假定的使用情况如下：
\begin{itemize}
\item 设置一个 run 标识数，

\item 登记一个统计图，

\item 设置灵敏探测器或数字化模块(e.g., dead channel)的指定运行条件。
\end{itemize}


\item endOfRunAction() 方法

这个方法在 beamOn() 结束的时候调用。典型的使用如下：
\begin{itemize}
\item 存储/输出 统计图，
\item 操作 run 摘要。
\end{itemize}
\end{itemize}


\subsection{GEANT4 as a state machine【Geant4 状态机】}

GEANT4 is designed as a state machine. Some methods in
GEANT4 are available for only a certain state(s). G4RunManager
controls the state changes of the GEANT4 application. States of
GEANT4 are represented by the enumeration G4ApplicationState. It
has six states through the life cycle of a GEANT4 application.

Geant4 被设计为一个状态机，某些方法仅在某个状态是可用的。 G4RunManager 控制 Geant4应用程序的状态改变， Geant4
的状态是用枚举量 G4ApplicationState 表示的。在一个 Geant4应用程序的整个生命周期中，一个有 6 个状态。

\textbf{G4State\_PreInit }state A GEANT4 application starts with
this state. The application needs to be initialized when it is in this state. The
application occasionally comes back to this state if geometry, physics processes,
and/or cut-off have been changed after processing a run.

\textbf{G4State\_Init }state The application is in this state while the
Initialize() method of G4RunManager is being invoked. Methods defined in any user
initialization classes are invoked during this state.

\textbf{G4State\_Idle }state The application is ready for starting a run.

\textbf{G4State\_GeomClosed }state When BeamOn() is invoked, the application
proceeds to this state to process a run. Geometry, physics processes, and cut-off
cannot be changed during run processing.

\textbf{G4State\_EventProc }state A GEANT4 application is in
this state when a particular event is being processed. GetCurrentEvent() and
GetPreviousEvent() methods of G4RunManager are available only at this state.

\textbf{G4State\_Quit }state When the destructor of G4RunManager is invoked, the
application comes to this ``dead end'' state. Managers of the GEANT4 kernel are being deleted and thus the application cannot come back to any
other state.

\textbf{G4State\_Abort }state When a G4Exception occurs, the application comes
to this ``dead end'' state and causes a core dump. The user still has a hook to
do some ``safe'' operations, e.g. storing histograms, by implementing a user
concrete class of G4VStateDependent. The user also has a choice to suppress the
occurrence of G4Exception by a UI command /control/suppressAbortion. When
abortion is suppressed, you will still get error messages issued by G4Exception,
and there is NO guarantee of a correct result after the G4Exception error
message.

G4StateManager belongs to the \textit{intercoms }category.

G4State\_PreInit state这是一个 Geant4 应用程序的开始状态。当应用程序在这种状态是，表明它需要初始化。应用程序在一个 run
之后，改变几何，物理过程，或者截断，也会使程序返回这个状态。

G4State\_Init state

在 G4RunManager 的方法 initialize()被调用的时候，应用程序进入这个状态。在这个状态下，在用户初始化类中定义的方法被调用。

G4State\_Idle state

这个状态表明应用程序准备开始模拟。

G4State\_GeomClosed state

当 beamOn() 被调用之后，应用程序进入到这个状态开始模拟。在这个状态下，用户不可以更改几何，物理过程，截断设置。

G4State\_EventProc state

当应用程序处理一个事件的时候，进入这个状态。 G4RunManager 的getCurrentEvent() 和 getPreviousEvent()
方法只有在这个状态下可用。

G4State\_Quit state

当 G4RunManager 的析构函数被调用的时候，应用程序进入到这个``终结''状态。Geant4 内核的 run Manager
正被删除，应用程序将不能回到任何其他状态。

G4State\_Abort state

当 G4Exception 发生的时候，应用程序进入到这个``终结''状态并引起一个内核丢弃。用户可以通过实现具体的
G4VStateDependent类，仍然可以利用一个
hook进行一些``安全''的操作，例如，存储统计图。用户也可以通过交互式命令/control/suppressAbortion选择限制 G4Exception
的发生。当例外被限制的时候，用户仍会受到 G4Exception 发出的错误信息，并且不保证在接到这些 G4Exception 错误信息之后的结果是正确的。

G4StateManager 属于 intercoms 类。


\subsection{User's hook for state change【用于状态改变时的用户 hook】}

{\raggedright
In case the user wants to do something at the moment of state change of
GEANT4, the user can create a concrete class of the
G4VStateDependent base class. For example, the user can store histograms when
G4Exception occurs and GEANT4 comes to the \textit{Abort }state,
but before the actual core dump.
}

{\raggedright
如果用户希望在 Geant4 状态改变时执行一些期望的指令，可以创建一个由G4VStateDependent 派生的类。例如，用户可以在 G4Exception
发生的时候，或者在 Geant4进入 Abort 状态的时候，在内核数据丢弃之前保存用户需要的统计数据。
}

The following is an example user code which stores histograms when
GEANT4 becomes to the \textit{Abort }state. This class object
should be made in, for example main(), by the user code. This object will be
automatically registered to G4StateManager at its construction.

下面是一个在 Geant4 进入 Abort 状态时用户保存统计数据的代码实例。这个类的对象应由用户创建，可以在 main()中。这个对象将在它创建的时候自动向
G4StateManager 注册。


\begin{lstlisting}[caption=Header file of UserHookForAbortState]
#ifndef UserHookForAbortState_H
#define UserHookForAbortState_H 1
#include "G4VStateDependent.hh"
class UserHookForAbortState : public G4VStateDependent
{
public:
UserHookForAbortState();   // constructor
~UserHookForAbortState(); // destructor
virtual G4bool Notify(G4ApplicationState requiredState);
};
\end{lstlisting}

\begin{lstlisting}[caption=Source file of UserHookForAbortState]
#include "UserHookForAbortState.hh"
UserHookForAbortState::UserHookForAbortState() {;}
UserHookForAbortState::~UserHookForAbortState() {;}
G4bool UserHookForAbortState::Notify(G4ApplicationState requiredState)
{
if(requiredState!=Abort) return true;
// Do book keeping here
return true;
}
\end{lstlisting}


\subsection{Customizing the Run Manager【定制 run Manager】}

\paragraph{Virtual Methods in the Run Manager【在 Run Manager 的虚拟方法】}

G4RunManager is a concrete class with a complete set of functionalities for
managing the GEANT4 kernel. It is the only manager class in the
GEANT4 kernel which must be constructed in the main() method of
the user's application. Thus, instead of constructing the G4RunManager provided
by GEANT4, you are free to construct your own RunManager. It is
recommended, however, that your RunManager inherit G4RunManager. For this
purpose, G4RunManager has various virtual methods which provide all the
functionalities required to handle the GEANT4 kernel. Hence, your
customized run manager need only override the methods particular to your needs;
the remaining methods in G4RunManager base class can still be used. A summary of
the available methods is presented here:

G4RunManager 是一个实类，是用于管理 G4 内核的各种功能的完整集合。它是 G4 内核中唯一的管理类，必须在用户应用程序的
main()函数中创建(构造)。用户也可以构造自己的RunManager ，来代替 G4 提供的 G4RunManager 。但是，用户的 RunManager
必需继承G4RunManager 。 G4RunManager 提供了各种用于管理 G4 内核的虚拟方法，用户在定制的RunManager
中只需要根据自己的需要重载这些方法就可以了，在基类 G4RunManager 中的其他方法同样可以继续使用。下面是这些虚拟方法：

\textbf{public: virtual void Initialize(); }main entry point of GEANT4 kernel initialization

\textbf{protected: virtual void InitializeGeometry(); }geometry construction

\textbf{protected: virtual void InitializePhysics(); }physics processes
construction

\textbf{public: virtual void BeamOn(G4int n\_event); }main entry point of the event loop

\textbf{protected: virtual G4bool ConfirmBeamOnCondition(); }check the kernel conditions for the event loop

\textbf{protected: virtual void RunInitialization(); }prepare a run

\textbf{protected: virtual void DoEventLoop(G4int n\_events); }manage an event
loop

\textbf{protected: virtual G4Event* GenerateEvent(G4int i\_event); }generation
of G4Event object

\textbf{protected: virtual void AnalyzeEvent(G4Event* anEvent);
}storage/analysis of an event

\textbf{protected: virtual void RunTermination(); }terminate a run

\textbf{public: virtual void DefineWorldVolume(G4VPhysicalVolume * worldVol);
}set the world volume to G4Navigator

\textbf{public: virtual void AbortRun(); }abort the run

{\raggedright
public: virtual void initialize();

G4 内核初始化的主入口
}

{\raggedright
protected: virtual void initializeGeometry();
}

{\raggedright
构造几何
}

{\raggedright
protected: virtual void initializePhysics();
}

{\raggedright
构造物理过程
}

{\raggedright
protected: virtual void initializeCutOff();
}

{\raggedright
设置反应产物截断值
}

{\raggedright
public: virtual void beamOn(G4int n\_event);
}

{\raggedright
事件循环主入口
}

{\raggedright
protected: virtual G4bool confirmBeamOnCondition();
}

{\raggedright
检查事件循环的内核状态
}

{\raggedright
protected: virtual void runInitialization();
}

{\raggedright
初始化一次 run
}

{\raggedright
protected: virtual void BuildPhysicsTables();
}

{\raggedright
更新区域信息并调用每个物理过程 建立/更新 物理表(physics tables)
}

{\raggedright
protected: virtual void doEventLoop(G4int n\_events);
}

{\raggedright
处理事件循环
}

{\raggedright
protected: virtual G4Event* generateEvent(G4int i\_event);
}

{\raggedright
生成 G4Event 对象
}

{\raggedright
protected: virtual void analyzeEvent(G4Event* anEvent);
}

{\raggedright
事件的保存分析
}

{\raggedright
protected: virtual void runTermination();
}

{\raggedright
中止 run
}

{\raggedright
public: virtual void defineWorldVolume(G4VPhysicalVolume * worldVol);
}

{\raggedright
为 G4Navigato 设置 world（世界）几何体 r
}

{\raggedright
public: virtual void abortRun();
}

{\raggedright
放弃运行
}

\paragraph{Customizing the Event Loop【定制事件循环】}

In G4RunManager the event loop is handled by the virtual method DoEventLoop().
This method is implemented by a for loop consisting of the following steps:

在 G4RunManager 中，事件循环是由虚方法 doEventLoop()进行处理的。这个方法由一个包括以下一些步骤的 for 循环实现：

\begin{enumerate}
	\item construct a G4Event object and assign to it primary vertex(es) and primary
particles. This is done by the virtual
\end{enumerate}

{\raggedright
GeneratePrimaryEvent() method.
}

\begin{enumerate}
	\item send the G4Event object to G4EventManager for the detector simulation.
\textit{Hits }and \textit{trajectories }will be associated with the G4Event
object as a consequence.
	\item perform bookkeeping for the current G4Event object. This is done by the virtual
AnalyzeEvent() method.
\end{enumerate}

DoEventLoop() performs the entire simulation of an event. However, it is often
useful to split the above three steps into isolated application programs. If, for
example, you wish to examine the effects of changing discriminator thresholds,
ADC gate widths and/or trigger conditions on simulated events, much time can be
saved by performing steps 1 and 2 in one program and step 3 in another. The first
program need only generate the hit/trajectory information once and store it,
perhaps in a database. The second program could then retrieve the stored G4Event
objects and perform the digitization (analysis) using the above threshold, gate
and trigger settings. These settings could then be changed and the digitization
program re-run without re-generating the G4Events.

1. 创建一个 G4Event 对象，并且指定初级粒子顶点和初级粒子。这些工作由虚方法generatePrimaryEvent() 完成。

2. 向 G4EventManager 发送一个 G4Event 对象，使 Hits 和 trajectories 与这个 G4Event对象相关联。

3. 针对当前 G4Event 对象，记录用户期望的数据。这将由虚方法 analyzeEvent() 来完成。

doEventLoop() 完成一个事件的整个模拟。然而，常常将上述的三个步骤分开放到相互独立的程序中。例如，如果用户需要检查改变被模拟事件的甄别阈、 ADC
门宽和触发条件后的变化，那么，将上述的前两步放在一个程序中，第 3 步放在另一个程序中，将会节约大量的机器时间。前一个程序只需要产生并保存
hit/trajectory 信息，第二个程序读取保存的
G4Event对象并用上述提到的阈值、门宽和触发条件进行数字化（分析），然后改变这些条件并再次进行数字化，而不需要再次运行第一个程序用于产生 G4Events。

\paragraph{Changing the Detector Geometry【改变探测器几何】}

The detector geometry defined in your G4VUserDetectorConstruction concrete class
can be changed during a run break (between two runs). Two different cases are
considered.

探测器几何在用户的 G4VUserDetectorConstruction 类中定义， 它可以在两个 run 之间进行更改。有两种不同的情况。

The first is the case in which you want to delete the entire structure of your
old geometry and build up a completely new set of volumes. For this case, you
need to delete them by yourself, and let \textit{RunManager }invokes Construct()
and ConstructSDandField() methods of your detector construction once again when
RunManager starts the next run.

第一中情况是，用户希望删除整个旧的几何结构并建立一个全新的结构。在这种情况下，用户需要向 RunManager 传递新的 world
几何体指针。因此，用户应该按如下的方法进行。

\begin{lstlisting}
G4RunManager* runManager = G4RunManager::GetRunManager();
runManager->ReinitializeGeometry();
\end{lstlisting}

If this ReinitializeGeometry() is invoked, GeometryHasBeenModified() (discussed
next) is automatically invoked. Presumably this case is rather rare. The second
case is more frequent for the user.

The second case is the following. Suppose you want to move and/or rotate a
particular piece of your detector component. This case can easily happen for a
beam test of your detector. It is obvious for this case that you need not change
the world volume. Rather, it should be said that your world volume (experimental
hall for your beam test) should be big enough for moving/rotating your test
detector. For this case, you can still use all of your detector geometries, and
just use a Set method of a particular physical volume to update the
transformation vector as you want. Thus, you don't need to re-set your world
volume pointer to \textit{RunManager}.

If you want to change your geometry for every run, you can implement it in the
BeginOfRunAction() method of G4UserRunAction class, which will be invoked at the
beginning of each run, or, derive the RunInitialization() method. Please note
that, for both of the above mentioned cases, you need to let \textit{RunManager
}know ``the geometry needs to be closed again''. Thus, you need to invoke

这种情况是相当少的，对于用户来说，第二种情况更常见。

第二种情况是这样的。假定用户需要移动、旋转探测器中的一个部分，这种情况常发生在束流测试试验中。很明显，用户不需要改变 world 几何体，更切确的说，用户的
world 几何体（对于束流试验中是试验大厅）足够大，可以在里面移动、旋转用户的探测器。对于这种情况，用户可以继续使用所有的探测器几何设置，只需要用相应物理体的
Set 方法更新一下相应的变换向量就可以了。不必重新向 RunManager 传递新的 world 几何体指针。

如果用户需要为每一个 run 改变几何设置，可以在 G4UserRunAction 类的方法beginOfRunAction() 中实现，它将在每次 run
开始前被调用；也可以派生runInitialization() 方法。请注意，上述的两种情况，用户需要让 RunManager 知道"thegeometry
needs to be closed again"。因此，在下一次 run 以前，用户需要调用

\begin{lstlisting}
runManager->GeometryHasBeenModified();
\end{lstlisting}

before proceeding to the next run. An example of changing geometry is given in a
GEANT4 tutorial in GEANT4 Training kit \#2.

在 Geant4 Training kit \#2 的 Geant4 tutorial 中给出了一个改变几何设置的实例。

\paragraph{Switch physics processes【切换（打开/关闭）物理过程】}

In the InitializePhysics() method, G4VUserPhysicsList::Construct is invoked in
order to define particles and physics processes in your application. Basically,
you can not add nor remove any particles during execution, because particles are
static objects in GEANT4 (see \textit{How to Specify Particles
}and \textit{Particles }for details). In addition, it is very difficult to add
and/or remove physics processes during execution, because registration procedures
are very complex, except for experts (see \textit{How to Specify Physics
Processes }and \textit{Physics Processes}). This is why the initializePhysics()
method is assumed to be invoked at once in GEANT4 kernel
initialization.

However, you can switch on/off physics processes defined in your
G4VUserPhysicsList concrete class and also change parameters in physics processes
during the run break.

You can use ActivateProcess() and InActivateProcess() methods of
G4ProcessManager anywhere outside the event loop to switch on/off some process.
You should be very careful to switch on/off processes inside the event loop,
though it is not prohibited to use these methods even in the \textit{EventProc
}state.

It is a likely case to change cut-off values in a run.
You can change defaultCutValue in
G4VUserPhysicsList during the \textit{Idle }state. In this case, all cross
section tables need to be recalculated before the event loop. You should use the
CutOffHasBeenModified() method when you change cut-off values so that the SetCuts
method of your \textit{PhysicsList }concrete class will be invoked.

在方法 initializePhysics() 中，通过调用 G4VUserPhysicsList::Construct
定义用户应用程序中使用的粒子和物理过程。由于 G4 中的粒子是静态对象(详情参看\textit{How to Specify
Particles}和\textit{Particles}
)，在程序执行过程中，用户不能增加或减少粒子。另外，要在程序执行过程中增加或减少物理过程也是非常困难的，因为注册过程非常复杂，初学者不宜使用(参看\textit{How
to Specify Physics Processes}和\textit{Physics Processes})。这就是为什么假定在 G4 内核初始化过程中方法
initializePhysics()立即被调用。

然而， 用户可以在两次 run 之间， 打开或者关闭在 G4VUserPhysicsList 类中定义的物理过程，改变物理过程的参数。

用户可以使用 G4ProcessManager 中的方法 ActivateProcess() 和 InActivateProcess()
，在事件循环以外的任何地方，切换一些物理过程。虽然，即使是在 EventProc
状态，都不禁止使用这些方法切换物理过程，但是，要在一个事件循环内部切换物理过程，用户必须十分的小心。

有时候，需要在一个 run 内部改变截断值。用户可以在 Idle 状态的时候，改变G4VUserPhysicsList 中的 defaultCutValue
。在这种情况下，所有的截面数据表必须在事件循环开始前重新计算。用户应该在改变截断值之后，调用方法 CutOffHasBeenModified() 来触发
InitializeCutOff() ， InitializeCutOff()将调用用户 PhysicsList 类中的方法SetCuts。


\subsection{Managing worker thread【管理工作线程】}

G4UserWorkerInitialization is an additional user initialization class to be used
only for the multithreaded mode. The object of this class can be set to
G4MTRunManager, but not to G4RunManager. G4UserWorkerInitialization class has
five virtual methods as the user hooks which are invoked at several occasions of
the life cycle of each thread.

G4UserWorkerInitialization是一个额外的用户初始化类，仅用于多线程模式。该类的对象可以设置为G4MTRunManager，但不能设置为G4RunManager。
G4UserWorkerInitialization类有五个虚拟方法作为用户挂钩，在每个线程的生命周期的几个场合中调用它们。

\textbf{virtual void WorkerInitialize() const }This method is called after the
tread is created but before the G4WorkerRunManager is instantiated.

\textbf{virtual void WorkerStart() const }This method is called once at the
beginning of simulation job when kernel classes and user action classes have
already instantiated but geometry and physics have not been yet initialized. This
situation is identical to ``PreInit'' state in the sequential mode.

\textbf{virtual void WorkerStartRun() const }This method is called before an
event loop. Geometry and physics have already been set up for the thread. All
threads are synchronized and ready to start the local event loop. This situation
is identical to ``Idle'' state in the sequential mode. \textbf{virtual void
WorkerRunEnd() const }This method is called for each thread when the local event
loop is done, but before the synchronization over all worker threads.

\textbf{virtual void WorkerStop() const }This method is called once at the end
of simulation job.

virtual void WorkerInitialize（）const在创建阶段之后但在G4WorkerRunManager实例化之前调用此方法。

virtual void
WorkerStart（）const当内核类和用户操作类已经实例化但几何和物理尚未初始化时，在模拟作业开始时调用此方法一次。这种情况与顺序模式下的``PreInit''状态相同。

virtual void
WorkerStartRun（）const在事件循环之前调用此方法。已经为该线程设置了几何和物理。所有线程都同步并准备启动本地事件循环。这种情况与顺序模式下的``空闲''状态相同。
virtual void WorkerRunEnd（）const当本地事件循环完成时，在所有工作线程同步之前，为每个线程调用此方法。

virtual void WorkerStop（）const在模拟作业结束时调用此方法一次。


\section{Event【事件】}

\subsection{Representation of an event}

G4Event represents an event. An object of this class contains all inputs and
outputs of the simulated event. This class object is constructed in G4RunManager
and sent to G4EventManager. The event currently being processed can be obtained
via the getCurrentEvent() method of G4RunManager.

G4Event 代表一个事件，它是一个包含所有被模拟事件的输入输出信息的类的实例。这个对象在 G4RunManager 中被创建并传递给
G4EventManager。可以通过 G4RunManager 的方法getCurrentEvent()获取当前正在处理的事件（指针）。

\subsection{Structure of an event【事件的结构】}

A G4Event object has four major types of information. Get methods for this
information are available in G4Event.

{\raggedright
Primary vertexes and primary particles Details are given in \textit{Event
Generator Interface}.
}

Trajectories Trajectories are stored in G4TrajectoryContainer class objects and
the pointer to this container is stored in G4Event. The contents of a trajectory
are given in \textit{Trajectory and Trajectory Point}.

Hits collections Collections of hits generated by \textit{sensitive detectors
}are kept in G4HCofThisEvent class object and the pointer to this container class
object is stored in G4Event. See \textit{Hits }for the details.

Digits collections Collections of digits generated by \textit{digitizer modules
}are kept in G4DCofThisEvent class object and the pointer to this container class
object is stored in G4Event. See \textit{Digitization }for the details.

一个 G4Event 对象有四类主要的信息。在 G4Event 中提供了这些信息的相应 Get 方法。初级事件顶点和初级粒子详情参看Event
Generator Interface节。

径迹粒子的径迹被保存在 G4TrajectoryContainer 类的实例中， 指向该对象的指针被保存在G4Event 中。径迹所包含的信息在
Trajectory and Trajectory Point中有叙述。

Hits collections由探测器(sensitive detectors)所产生的 hits 被保存在 G4HCofThisEvent 类的实例中，
指向它的指针同样被存储在 G4Event 中，详情请看Hits节。

Digits collections由 digitizer modules 产生的 digits 信息被保存在 G4DCofThisEvent
类的实例中，指向该对象的指针也存储在 G4Event 中，详情参看Digitization节

\subsection{Mandates of G4EventManager【G4EventManager 的要求】}

G4EventManager is the manager class to take care of one event. It is responsible
for:

G4EventManager 是管理事件对象的管理类，主要完成以下任务：

\begin{itemize}
	\item converting G4PrimaryVertex and G4PrimaryParticle objects associated with the current G4Event object to G4Track objects. All of G4Track objects representing the primary particles are sent to G4StackManager.

	\item Pop one G4Track object from G4StackManager and send it to G4TrackingManager. The current G4Track object is deleted by G4EventManager after the track is simulated by G4TrackingManager, if the track is marked as ``killed''.
	\item In case the primary track is ``suspended'' or ``postponed to next event'' by G4TrackingManager, it is sent back to the G4StackManager. Secondary G4Track objects returned by G4TrackingManager are also sent to G4StackManager.
	\item When G4StackManager returns NULL for the ``pop'' request, G4EventManager terminates the current processing event.
	\item invokes the user-defined methods beginOfEventAction() and endOfEventAction() from the G4UserEventAction class. See \textit{User Information Classes }for details.
\end{itemize}


\vspace{2cm}
\begin{itemize}
\item  将与当前 G4Event 事件对象有关的 G4PrimaryVertex 和 G4PrimaryParticle 对象转换为
G4Track 对象。所有代表初级粒子的 G4Track 对象被传递给 G4StackManager。

\item  从 G4StackManager 中弹出一个 G4Track 对象并传递给
G4TrackingManager。如果径迹(track)在被 G4TrackingManager 模拟之后，被标记为``killed''，那么该 G4Track
对象将被 G4EventManager 删除。Geant4 User's Guide or Application DevelopersToolkit
Fundamentals

\item  如果初级 track 被 G4TrackingManager "suspended" 或者 "postponed to next
event"，那么这个 track 将被重新压入 G4StackManager，由 G4TrackingManager 返回的次级G4Track 对象也被压入
G4StackManager。

\item  当 G4StackManager 对出栈请求的响应返回 NULL 的时候， G4EventManager 将中止当前的处理过程。

\item  从 G4UserEventAction 类中调用用户自定义的方法 beginOfEventAction()
和endOfEventAction()，详情参看\textit{User Information Classes}节。

\end{itemize}

\subsection{Stacking mechanism【栈机制】}

G4StackManager has three stacks, named \textit{urgent}, \textit{waiting }and
\textit{postpone-to-next-event}, which are objects of the G4TrackStack class. By
default, all G4Track objects are stored in the \textit{urgent }stack and handled
in a ``last in first out'' manner. In this case, the other two stacks are not
used. However, tracks may be routed to the other two stacks by the user-defined
G4UserStackingAction concrete class.

If the methods of G4UserStackingAction have been overridden by the user, the
\textit{postpone-to-next-event }and \textit{waiting }stacks may contain tracks.
At the beginning of an event, G4StackManager checks to see if any tracks left
over from the previous event are stored in the \textit{postpone-to-next-event
stack}. If so, it attempts to move them to the \textit{urgent }stack. But first
the PrepareNewEvent() method of G4UserStackingAction is called. Here tracks may
be re-classified by the user and sent to the \textit{urgent }or \textit{waiting
}stacks, or deferred again to the \textit{postpone-to-next-event }stack. As the
event is processed G4StackManager pops tracks from the \textit{urgent }stack
until it is empty. At this point the NewStage() method of G4UserStackingAction is
called. In this method tracks from the \textit{waiting }stack may be sent to the
\textit{urgent }stack, retained in the \textit{waiting }stack or postponed to the
next event.

Details of the user-defined methods of G4UserStackingAction and how they affect
track stack management are given in \textit{User Information Classes}.

G4StackManager 共有 3 个栈，分别是 urgent, waiting 和 postpone-to-next-event,
它们都是G4TrackStack 类的实例。缺省情况下，所有的 G4Track 对象被保存在 urgent
栈中，以后进先出的方式工作。在这种情况下，其余两个栈没有被使用。但是，通过用户自定义的G4UserStackingAction 类， tracks
可能会被发送到其余两个栈中。

如果 G4UserStackingAction 的方法已经被用户重载，那么， postpone-to-next-event 栈和waiting 栈中也可能又
tracks 存在。在一个事件开始的时刻， G4StackManager 将检查postpone-to-next-event 栈，看是否有前一事件余留下来的
tracks。如果有的话，它会将这些tracks 转移到 urgent 栈中。 当然，首先需要调用 G4UserStackingAction
的方法PrepareNewEvent() ，然后， traks 将可能被用户重新分类并将它们压入 urgent 或者 waiting栈，或者重新压入
postpone-to-next-event ，等待下一事件的处理。在事件被处理的时候，G4StackManager 从 urgent 栈中逐个弹出所有的
tracks。接着， G4UserStackingAction 中的方法 NewStage() 将被调用。在这个方法中，在waiting 栈中的
tracks可能被发送到 urgent 栈，也可能继续保留在 waiting 栈中，或者被压入到 postpone-to-next-event
栈中，延迟到下一个事件。

有关 G4UserStackingAction 中的用户自定义方法的详情，以及它们如何影响 track 栈的管理在 6.2 节中有叙述。

\section{Event Generator Interface【事件发生器接口】}

\subsection{Structure of a primary event【初级事件结构】}

\paragraph{Primary vertex and primary particle【初级粒子顶点和初级粒子】}
The G4Event class object should have a set of primary particles when it is sent
to G4EventManager via processOneEvent() method. It is the mandate of your
G4VUserPrimaryGeneratorAction concrete class to send primary particles to the
G4Event object.

The G4PrimaryParticle class represents a primary particle with which
GEANT4 starts simulating an event. This class object has
information on particle type and its three momenta. The positional and time
information of primary particle(s) are stored in the G4PrimaryVertex class object
and, thus, this class object can have one or more G4PrimaryParticle class objects
which share the same vertex. Primary vertexes and primary particles are
associated with the G4Event object by a form of linked list.

A concrete class of G4VPrimaryGenerator, the G4PrimaryParticle object is
constructed with either a pointer to G4ParticleDefinition or an integer number
which represents P.D.G. particle code. For the case of some artificial particles,
e.g., geantino, optical photon, etc., or exotic nuclear fragments, which the
P.D.G. particle code does not cover, the G4PrimaryParticle should be constructed
by G4ParticleDefinition pointer. On the other hand, elementary particles with
very short life time, e.g., weak bosons, or quarks/gluons, can be instantiated as
G4PrimaryParticle objects using the P.D.G. particle code. It should be noted
that, even though primary particles with such a very short life time are defined,
GEANT4 will simulate only the particles which are defined as

G4ParticleDefinition class objects. Other primary particles will be simply
ignored by G4EventManager. But it may still be useful to construct such
``intermediate'' particles for recording the origin of the primary event.

在通过方法 processOneEvent() 将 G4Event 对象发送给 G4EventManager 的时候，必须保证这个 G4Event
对象已拥有一些初级粒子，这些初级粒子是由用户的4VUserPrimaryGeneratorAction 类发送给 G4Event 对象的。

G4PrimaryParticle 类代表 Geant4 开始模拟一个事件的初级粒子。这个类的实例拥有有关粒子类型及它的动量等信息，相关的位置与时间信息被保存在
G4PrimaryVertex 对象中，这样做的好处是，一个或多个 G4PrimaryParticle
对象可以共享同一个顶点。初级粒子顶点与初级粒子通过一个链表与 G4Event 对象相关联。

G4PrimaryParticle 是 G4VPrimaryGenerator 类的一个具体类，需要通过指向G4ParticleDefinition
的一个指针，或者一个表示 P.D.G. 粒子代码的整数，来创建它的实例。对于某些假粒子的情况，如： geantino ，光学光子（optical
photon）等,或者一些在 P.D.G. 粒子代码中不存在的奇异的核碎片， G4PrimaryParticle 对象应该通过
G4ParticleDefinition 指针来构造。另外，那些短寿命的基本粒子，如，弱玻色子，或者夸克/胶子，可以使用 P.D.G.粒子代码将这些粒子作为
G4PrimaryParticle 对象实例化。需要注意的是， Geant4 只模拟那些作为 G4ParticleDefinition
对象定义的粒子，其余的初级粒子将会被 G4EventManager
忽略。但是，如果要记录初级事件的起始点，定义一些中间(``intermediate'')粒子是非常有用的。

\paragraph{Forced decay channel【强迫衰变通道】}

The G4PrimaryParticle class object can have a list of its daughter particles. If
the parent particle is an ``intermediate'' particle, which GEANT4
does not have a corresponding G4ParticleDefinition, this parent particle is
ignored and daughters are assumed to start from the vertex with which their
parent is associated. For example, a Z boson is associated with a vertex and it
has positive and negative muons as its daughters, these muons will start from
that vertex.

There are some kinds of particles which should fly some reasonable distances
and, thus, should be simulated by GEANT4, but you still want to
follow the decay channel generated by an event generator. A typical case of these
particles is B meson. Even for the case of a primary particle which has a
corresponding G4ParticleDefinition, it can have daughter primary particles.
GEANT4 will trace the parent particle until it comes to decay,
obeying multiple scattering, ionization loss, rotation with the magnetic field,
etc. according to its particle type. When the parent comes to decay, instead of
randomly choosing its decay channel, it follows the ``pre-assigned'' decay
channel. To conserve the energy and the momentum of the parent, daughters will be
Lorentz transformed according to their parent's frame.

G4PrimaryParticle 对象可以有一系列的次级粒子。如果一个粒子是一个中间粒子，它没有对应的 G4ParticleDefinition，
那么，这个粒子将被忽略，而它的次级粒子的定点将被假定为与该粒子的顶点相同。 例如， 一个 Z 玻色子和它的次级粒子，
一个正$\mu{}$介子和一个负$\mu{}$介子，这两个$\mu{}$介子将被认为是从 Z 玻色子的那个顶点出发的。

有些粒子有相应的飞行距离， Geant4 模拟的时候应考虑这些，但有的时候，用户还希望跟踪由事件发生器产生的衰变通道。比较典型的情况是 B
介子。甚至是有相应的G4ParticleDefinition,可以产生次级粒子。 Geant4
将跟踪这个粒子，直到它发生衰变，根据粒子的类型，判断是否发生多次散射，电离损失，在磁场中偏转。当粒子发生衰变的时候，它将向``预设''的衰变通道发生衰变，而不是用随机选择的办法选择衰变通道。为了转换粒子的动量和能量，次级粒子将根据初级粒子具体情况进行洛伦茨变换。


\subsection{Interface to a primary generator【初级事件发生器接口】}

\paragraph{G4HEPEvtInterface}

Unfortunately, almost all event generators presently in use, commonly are
written in FORTRAN. For GEANT4, it was decided to not link with
any FORTRAN program or library, even though the C++ language syntax itself allows
such a link. Linking to a FORTRAN package might be convenient in some cases, but
we will lose many advantages of object-oriented features of C++, such as
robustness. Instead, GEANT4 provides an ASCII file interface for
such event generators.

G4HEPEvtInterface is one of G4VPrimaryGenerator concrete class and thus it can
be used in your G4VUserPrimaryGeneratorAction concrete class. G4HEPEvtInterface
reads an ASCII file produced by an event generator and reproduces
G4PrimaryParticle objects associated with a G4PrimaryVertex object. It reproduces
a full production chain of the event generator, starting with primary quarks,
etc. In other words, G4HEPEvtInterface converts information stored in the
/HEPEVT/ common block to an object-oriented data structure. Because the /HEPEVT/
common block is commonly used by almost all event generators written in FORTRAN,
G4HEPEvtInterface can interface to almost all event generators currently used in
the HEP community. The constructor of G4HEPEvtInterface takes the file name.
Listing 3.3 shows an example how to use G4HEPEvtInterface. Note that an event
generator is not assumed to give a place of the primary particles, the
interaction point must be set before invoking GeneratePrimaryVertex() method.

不幸的是，几乎目前所有正在使用的事件发生器都是用 FORTRAN 写的。对于 G4 来说，不希望与任何 FORTRAN 程序或者库进行连接，即使
C++本身允许这样做。在某些情况下，与FORTRAN 程序包链接非常方便，但是，我们将失去很多 C++面向对象的优点，例如，程序的稳健性（）。因此， G4
只提供了一个 ASCII 文件接口来实现事件发生器。

G4HEPEvtInterface 是 G4VPrimaryGenerator
的一个具体类，它可以在用户的G4VUserPrimaryGeneratorAction 相应实类中使用。 G4HEPEvtInterface
将读取由事件发生器产生的 ASCII 文件，并生成与 G4PrimaryVertex 对象相关联的 G4PrimaryParticle 对象。

G4HEPEvtInterface 将保存在公用块/HEPEVT/ 的信息转换为一个面向对象的数据结构。由于公用块/HEPEVT/几乎被所有用 FORTRAN
写的事件发生器所使用， 所以， G4HEPEvtInterface几乎可以与所有目前在 HEP 领域所使用的事件发生器进行接口。
G4HEPEvtInterface 的构造函数使用文件名作为参数。代码清单 3.6.1 列出了一个如何使用 G4HEPEvtInterface
的实例。注意，事件发生器并不假定提供初级粒子的位置，这个位置必须在调用方法GeneratePrimaryVertex() 之前被设置。


\begin{lstlisting}[caption=An example code for G4HEPEvtInterface]
#ifndef ExN04PrimaryGeneratorAction_h
#define ExN04PrimaryGeneratorAction_h 1
#include "G4VUserPrimaryGeneratorAction.hh"
#include "globals.hh"
class G4VPrimaryGenerator;
class G4Event;
class ExN04PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction
{
public:
ExN04PrimaryGeneratorAction();
~ExN04PrimaryGeneratorAction();
public:
void GeneratePrimaries(G4Event* anEvent);
private:
G4VPrimaryGenerator* HEPEvt;
};
#endif
#include "ExN04PrimaryGeneratorAction.hh"
#include "G4Event.hh"
#include "G4HEPEvtInterface.hh"
ExN04PrimaryGeneratorAction::ExN04PrimaryGeneratorAction()
{
HEPEvt = new G4HEPEvtInterface("pythia_event.data");
}
ExN04PrimaryGeneratorAction::~ExN04PrimaryGeneratorAction()
{
delete HEPEvt;
}
void ExN04PrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{
HEPEvt->SetParticlePosition(G4ThreeVector(0.*cm,0.*cm,0.*cm));
HEPEvt->GeneratePrimaryVertex(anEvent);
}
\end{lstlisting}


\paragraph{Format of the ASCII file【ASCII 文件格式】}

An ASCII file, which will be fed by G4HEPEvtInterface should have the following
format.

一个将被 G4HEPEvtInterface 写的 ASCII 文件应有如下格式。

\begin{itemize}
	\item The first line of each primary event should be an integer which represents the
number of the following lines of primary particles.
	\item Each line in an event corresponds to a particle in the /HEPEVT/ common. Each
line has ISTHEP, IDHEP,
\end{itemize}
{\raggedright
JDAHEP(1), JDAHEP(2), PHEP(1), PHEP(2), PHEP(3), PHEP(5). Refer to the /HEPEVT/
manual for the meanings of these variables.
}

{\raggedright
\textbullet{} 每个初级事件的第一行应为一个整数，表示后续有多少行初级粒子数据。
}

{\raggedright
\textbullet{} 在一个事件中的每一行对应于一个在/HEPEVT/ 公用块中的粒子。每一行有 ISTHEP,IDHEP, JDAHEP(1),
JDAHEP(2), PHEP(1), PHEP(2), PHEP(3), PHEP(5)。 有关这些变量的含义请参阅/HEPEVT/ 的手册。
}
Listing 3.4 shows an example FORTRAN code to generate an ASCII file.

代码清单 3.4 显示了一个生成 ASCII 文件的 FORTRAN 代码实例。

\begin{lstlisting}[caption=Ashows an example FORTRAN code to generate an ASCII file.]
***********************************************************
SUBROUTINE HEP2G4
*
* Convert /HEPEVT/ event structure to an ASCII file
* to be fed by G4HEPEvtInterface
*
***********************************************************
PARAMETER (NMXHEP=2000)
COMMON/HEPEVT/NEVHEP,NHEP,ISTHEP(NMXHEP),IDHEP(NMXHEP),
>JMOHEP(2,NMXHEP),JDAHEP(2,NMXHEP),PHEP(5,NMXHEP),VHEP(4,NMXHEP)
DOUBLE PRECISION PHEP,VHEP
*
WRITE(6,*) NHEP
DO IHEP=1,NHEP
WRITE(6,10)
> ISTHEP(IHEP),IDHEP(IHEP),JDAHEP(1,IHEP),JDAHEP(2,IHEP),
> PHEP(1,IHEP),PHEP(2,IHEP),PHEP(3,IHEP),PHEP(5,IHEP)
10
FORMAT(4I10,4(1X,D15.8))
ENDDO
RETURN
END
\end{lstlisting}

\paragraph{Future interface to the new generation generators【未来新的事件发生器接口】}

Several activities have already been started for developing object-oriented
event generators. Such new generators can be easily linked and used with a
GEANT4 based simulation. Furthermore, we need not distinguish a
primary generator from the physics processes used in GEANT4.
Future generators can be a kind of physics process plugged-in by inheriting
G4VProcess.

目前已经开始开发面向对象的事件发生器。这些新的事件发生器可以非常容易与基于 G4 的应用程序相链接。另外，我们在 G4
中不用区分初级事件发生器和其他物理过程，未来的发生器可能就是一个从 G4VProcess 继承的物理过程。

\subsection{Event overlap using multiple generators【使用多个事件发生器的事件复合】}

Your G4VUserPrimaryGeneratorAction concrete class can have more than one
G4VPrimaryGenerator concrete class. Each G4VPrimaryGenerator concrete class can
be accessed more than once per event. Using these class objects, one event can
have more than one primary event.

One possible use is the following. Within an event, a G4HEPEvtInterface class
object instantiated with a minimum bias event file is accessed 20 times and
another G4HEPEvtInterface class object instantiated with a signal event file is
accessed once. Thus, this event represents a typical signal event of LHC
overlapping 20 minimum bias events. It should be noted that a simulation of event
overlapping can be done by merging hits and/or digits associated with several
events, and these events can be simulated independently. Digitization over
multiple events will be mentioned in \textit{Digitization}.

用户 G4VUserPrimaryGeneratorAction 类的具体类可以拥有多个 G4VPrimaryGenerator 类的具体类。每个
G4VPrimaryGenerator 类的具体类可以在同一事件过程中使用多次。通过使用这些对象，一个事件可以有多个初级事件组成。

一种可能的使用情况如下。在一个事件内部，一个使用最小偏倚事件文档初始化的G4HEPEvtInterface 类对像被存取 20
次，另一个使用信号事件文档初始化的G4HEPEvtInterface 类对像被存取一次。因而，这个事件表示一个典型的与 20 个最小偏倚事件复合的
LHC信号事件。需要注意的是，事件复合的模拟可以通过合并与多个事件相关的hits和/或 digits 来实现， 并且这些事件是可以独立模拟的。在
\textit{Digitization}节中谈到了多个事件的数字化。

\section{Event Biasing Techniques【事件偏倚技巧】}

\subsection{Scoring, Geometrical Importance Sampling and Weight Roulette【Scoring，几何重要性采样和权重轮盘赌】}

GEANT4 provides event biasing techniques which may be used to
save computing time in such applications as the simulation of radiation
shielding. These are \textit{geometrical splitting }and \textit{Russian roulette
}(also called geometrical importance sampling), and \textit{weight roulette}.
Scoring is carried out by G4MultiFunctionalDetector (see
\textit{G4MultiFunctionalDetector and G4VPrimitiveScorer }and \textit{Concrete
classes of G4VPrimitiveScorer}) using the standard GEANT4 scoring
technique. Biasing specific scorers have been implemented and are described
within G4MultiFunctionalDetector documentation. In this chapter, it is assumed
that the reader is familiar with both the usage of GEANT4 and the
concepts of importance sampling. More detailed documentation may be found in the
documents
\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/Sampling.html}{`Scoring,
geometrical importance sampling and weight
roulette'}.
A detailed description of different use-cases which employ the sampling and
scoring techniques can be found in the document
\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/BiasScoreUseCases.html}{`Use
cases of importance
}\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/BiasScoreUseCases.html}{sampling
and scoring in Geant4'}.

The purpose of importance sampling is to save computing time by sampling less
often the particle histories entering ``less important'' geometry regions, and
more often in more ``important'' regions. Given the same amount of computing
time, an importance-sampled and an analogue-sampled simulation must show equal
mean values, while the importance-sampled simulation will have a decreased
variance.

The implementation of scoring is independent of the implementation of importance
sampling. However both share common concepts. \textit{Scoring and importance
sampling apply to particle types chosen by the user}, which should be borne in
mind when interpreting the output of any biased simulation.

Examples on how to use scoring and importance sampling may be found in
examples/extended/biasing.

G4
提供了使用几何分裂和俄罗斯轮盘赌（也叫几何重要性采样）以及权重轮盘赌的可能性。这些技巧用于节约计算机模拟的机时。G4提供了一个基本的Scoring系统用于监视这些采样。在这一章中，我们假定读者对重要性采样和
G4
的使用都很熟悉。有关详细的文档可以在\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/Sampling.html}{`Scoring,
geometrical importance sampling and weight
roulette'}找到。使用这些采样和记录技巧的各种情况的详细描述，可以在\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/BiasScoreUseCases.html}{`Use
cases of importance
}\href{http://geant4.cern.ch/collaboration/working\_groups/geometry/biasing/BiasScoreUseCases.html}{sampling
and scoring in Geant4'}中找到。

Scoring 用于估计与特定区域或表面相关的粒子的数量，应用于给定几何体的所有"cells" (物理体或其副本) 。Scoring
需要用户定制，除它为某些量（例如：径迹进入一个 cell 的数量，进入径迹的平均权重，进入径迹的能量，在 cell 内部的碰撞次数。）提供的标准
scoring。重要性采样的目的是通过较多的采样比较``重要''的几何区域，较少的采样比较``不重要''的几何区域，来节约计算时间。采用重要性采样后的结果与原来的结果相比较，他们的平均值一定相等，但是对于相同的计算时间，前者的方差将显著减小。

Scoring 的实现与重要性采样的实现是相互独立的。但是两者有一些共同的概念。 Scoring 和重要性采样应用于用户指定的粒子类型。

关于如何使用 scoring 和重要性采样的例子在 examples/extended/biasing。
\paragraph{Geometries【几何体】}

The kind of scoring referred to in this note and the importance sampling apply
to spatial cells provided by the user.

这里提到的 scoring 和重要性采样应用于用户指定的空间 cells。

A cell is a physical volume (further specified by it's replica number, if the
volume is a replica). Cells may be defined in two kinds of geometries:

一个 cell 是一个物理体(如果是副本，需要通过复制序号指定)。这些单元可以定义为两种类型的几何体：

\begin{enumerate}
	\item mass geometry: the geometry setup of the experiment to be simulated. Physics processes apply to this geometry.
	\item parallel-geometry: a geometry constructed to define the physical volumes according to which scoring and/or importance sampling is applied.
\end{enumerate}
\vspace{1cm}
\begin{enumerate}
\item mass geometry: 试验中将被模拟的几何体，物理过程将应用到这些几何体中。
\item parallel-geometry: 这类几何体是根据它们所应用的记录和重要性采样而定义的几何体，它们并不是传统意义上的真实的物理几何体。
\end{enumerate}

The user has the choice to score and/or sample by importance the particles of
the chosen type, according to mass geometry or to parallel geometry. It is
possible to utilize several parallel geometries in addition to the mass geometry.
This provides the user with a lot of flexibility to define separate geometries
for different particle types in order to apply scoring or/and importance
sampling.

根据 mass geometry 或者 parallel geometry, 用户选择相应粒子的重要性进行记录和采样。对于相同的 mass
geometry，可以使用多个 parallel geometry，对不同的粒子定义相互独立的，使用不同记录和重要性采样的 parallel
geometry，这给用户提供了更大的灵活性。




\rule{\textwidth}{1 pt}
\begin{flushleft}
Note: Parallel geometries should be constructed using the implementation as
described in \textit{Parallel Geometries}. There are a few conditions for
parallel geometries:

注意：并行几何应该使用\textit{Parallel Geometries}中描述的来实现构造。 平行几何有几个条件：

\begin{itemize}
	\item The world volume for parallel and mass geometries must be identical copies.
	\item Scoring and importance cells must not share boundaries with the world volume.
\end{itemize}
\vspace{1cm}
\begin{itemize}
\item 平行和质量几何体的世界体必须相同。
\item 计数器和重要性cell不得与世界体存在共同边界。
\end{itemize}
\end{flushleft}
\rule{\textwidth}{1 pt}

Samplers are higher level tools which perform the necessary changes of the
GEANT4 sampling in order to apply importance sampling and weight
roulette.

Variance reduction (and scoring through the G4MultiFunctionalDetector) may be
combined arbitrarily for chosen particle types and may be applied to the mass or
to parallel geometries.

The G4GeometrySampler can be applied equally to mass or parallel geometries with
an abstract interface supplied by G4VSampler. G4VSampler provides Prepare...
methods and a Configure method:

取样器是更高层次的工具，它对 G4 的取样过程作一些必要的变化，以便于使用重要性采样和权重轮盘赌。取样器可以应用于 scoring。

Scoring 和方差减小这两种技巧可以任意的组合，应用于特定的粒子类型，和 mass 几何体或者 parallel 几何体。取样器支持所有的组合。

需要为 mass 几何体和 parallel 几何体实现不同的取样器。两者实现了接口 G4VSampler，G4VSampler 允许准备（prepare）
scoring 及方差减小的特定组合，和配置（configure）适当的采样过程。为此， G4VSampler 提供相应的方法 Prepare 和
Configure ：

\begin{lstlisting}
class G4VSampler
{
public:
G4VSampler();
virtual ~G4VSampler();
virtual void PrepareImportanceSampling(G4VIStore *istore,
const G4VImportanceAlgorithm
*ialg = 0) = 0;
virtual void PrepareWeightRoulett(G4double wsurvive = 0.5,
G4double wlimit = 0.25,
G4double isource = 1) = 0;
virtual void PrepareWeightWindow(G4VWeightWindowStore *wwstore,
G4VWeightWindowAlgorithm *wwAlg = 0,
G4PlaceOfAction placeOfAction =
onBoundary) = 0;
virtual void Configure() = 0;
virtual void ClearSampling() = 0;
virtual G4bool IsConfigured() const = 0;
};
\end{lstlisting}

The methods for setting up the desired combination need specific information:

建立期望组合的方法需要指定以下信息:

\begin{itemize}
	\item Importance sampling:
	message  PrepareImportanceSampling with a G4VIStore and optionally a G4VImportanceAlgorithm
	
	重要性采样:向 PrepareImportanceSampling 发送一个 G4VIStore 消息和一个可选的G4VImportanceAlgorithm消息
	
\item  Weight window:
message PrepareWeightWindow with the arguments:

权重窗口：带参数的消息PrepareWeightWindow：

\begin{itemize}
	\item \textit{*wwstore}:
	a G4VWeightWindowStore for retrieving the lower weight bounds
for the energy-space cells

一个G4VWeightWindowStore，用于获取能量空间单元的权重下限
	\item \textit{*wwAlg}:
	a G4VWeightWindowAlgorithm if a customized algorithm should be used
	
	一个G4VWeightWindowAlgorithm，如果应该使用自定义的算法
	\item \textit{placeOfAction}:
	a G4PlaceOfAction specifying where to perform the biasing
	
	一个G4PlaceOfAction，指定执行偏置的位置
\end{itemize}

\item Weight roulette:

message PrepareWeightRoulett with the optional parameters:

权重轮盘赌：向 PrepareWeightRoulett 发送以下可选消息：

\begin{itemize}
	\item \textit{wlimit}:
	
	minimal allowed value of weight * source importance / cell
importance
	\item \textit{isource}:
	
	importance of the source cell
\end{itemize}
\end{itemize}

Each object of a sampler class is responsible for one particle type. The
particle type is given to the constructor of the sampler classes via the particle
type name, e.g. ``neutron''. Depending on the specific purpose, the Configure()
of a sampler will set up specialized processes (derived from G4VProcess) for
transportation in the parallel geometry, importance sampling and weight roulette
for the given particle type. When Configure() is invoked the sampler places the
processes in the correct order independent of the order in which user invoked the
Prepare... methods.

一个取样器类的每个对象对应于一种粒子类型。这种粒子类型通过粒子类型名（如，"neutron"）向取样器类的构造函数指定。对于特定的用途，一个取样器的
Configure() 方法将为给定的粒子类型建立一些特定的过程，这些过程从 G4VProcess 派生；用于在 parallel 几何体中的输运、
scoring、重要性采样和权重轮盘赌。当 Configure() 被调用的时候，取样器将这些过程安相应正确的顺序放置，使它们与用户使用 Prepare
方法调用的顺序无关。

\rule{\textwidth}{1 pt}
\begin{flushleft}
Note:
\begin{itemize}
	\item The Prepare...() functions may each only be invoked once.
	
	Prepare() 函数每一个只能调用一次。
	\item To configure the sampling the function Configure() must be called \textit{after } the G4RunManager has been initialized and the PhysicsList has been instantiated.
	
	为了配置取样过程， Configure() 一定要在 G4RunManager 已经被初始化之后被调用。
\end{itemize}
\end{flushleft}
\rule{\textwidth}{1 pt}

The interface and framework are demonstrated in the examples/extended/biasing
directory, with the main changes being to the G4GeometrySampler class and the
fact that in the parallel case the WorldVolume is a copy of the Mass World. The
parallel geometry now has to inherit from G4VUserParallelWorld which also has the
GetWorld() method in order to retrieve a copy of the mass geometry WorldVolume.

接口和框架在examples / extended /
biasing目录中进行了演示，其中主要更改为G4GeometrySampler类，并且WorldVolume是Mass World的副本。
平行几何现在必须从也具有GetWorld（）方法的G4VUserParallelWorld继承，以便检索质量几何体WorldVolume的副本。

\begin{lstlisting}
class B02ImportanceDetectorConstruction : public G4VUserParallelWorld
ghostWorld = GetWorld();
\end{lstlisting}

The constructor for G4GeometrySampler takes a pointer to the physical world
volume and the particle type name (e.g. ``neutron'') as arguments. In a single
mass geometry the sampler is created as follows:

G4GeometrySampler的构造函数将一个指向物理世界体的指针和粒子类型名称（例如``neutron''）作为参数。
在单个质量几何体中，采样器创建如下：

\begin{lstlisting}
G4GeometrySampler mgs(detector->GetWorldVolume(),"neutron");
mgs.SetParallel(false);
\end{lstlisting}

Whilst the following lines of code are required in order to set up the sampler
for the parallel geometry case:

虽然为了设置平行几何例子的采样器需要以下几行代码：

\begin{lstlisting}
G4VPhysicalVolume* ghostWorld = pdet->GetWorldVolume();
G4GeometrySampler pgs(ghostWorld,"neutron");
pgs.SetParallel(true);
\end{lstlisting}

Also note that the preparation and configuration of the samplers has to be
carried out \textit{after }the instantiation of the UserPhysicsList. With the
modular reference PhysicsList the following set-up is required (first is for
biasing, the second for scoring):

还要注意，采样器的准备和配置必须在实例化UserPhysicsList之后执行。 使用模块化参考物理学列表，需要进行以下设置（首先进行偏置，第二次进行计数）：

\begin{lstlisting}
physicsList->RegisterPhysics(new G4ImportanceBiasing(\&pgs,parallelName));
physicsList->RegisterPhysics(new G4ParallelWorldPhysics(parallelName));
\end{lstlisting}

If the a UserPhysicsList is being implemented, then the following should be used
to give the pointer to the GeometrySampler to the PhysicsList:

如果正在实现一个UserPhysicsList，那么应该使用以下指令将指向GeometrySampler的指针指向PhysicsList：


\begin{lstlisting}
physlist->AddBiasing(\&pgs,parallelName);
\end{lstlisting}

Then to instantiate the biasing physics process the following should be included
in the UserPhysicsList and called from ConstructProcess():

然后为了实例化偏置物理过程，应在UserPhysicsList中包含以下内容并从ConstructProcess（）中调用：

\begin{lstlisting}
AddBiasingProcess(){
fGeomSampler->SetParallel(true); // parallelworld
G4IStore* iStore = G4IStore::GetInstance(fBiasWorldName);
fGeomSampler->SetWorld(iStore->GetParallelWorldVolumePointer());
// fGeomSampler->PrepareImportanceSampling(G4IStore::
//
GetInstance(fBiasWorldName), 0);
static G4bool first = true;
if(first) {
fGeomSampler->PrepareImportanceSampling(iStore, 0);
fGeomSampler->Configure();
G4cout << " GeomSampler Configured!!! " << G4endl;
first = false;
}
#ifdef G4MULTITHREADED
fGeomSampler->AddProcess();
#else
G4cout << " Running in singlethreaded mode!!! " << G4endl;
#endif
\end{lstlisting}


\begin{lstlisting}
pgs.PrepareImportanceSampling(G4IStore::GetInstance(pdet->GetName()), 0);
pgs.Configure();
\end{lstlisting}

Due to the fact that biasing is a process and has to be inserted after all the
other processes have been created.

由于偏置是一个过程，必须在创建所有其他过程之后才能插入。

\paragraph{Importance Sampling【重要性采样】}

Importance sampling acts on particles crossing boundaries between ``importance
cells''. The action taken depends on the importance values assigned to the cells.
In general a particle history is either split or Russian roulette is played if
the importance increases or decreases, respectively. A weight assigned to the
history is changed according to the action taken.

The tools provided for importance sampling require the user to have a good
understanding of the physics in the problem. This is because the user has to
decide which particle types require importance sampled, define the cells, and
assign importance values to the cells. If this is not done properly the results
cannot be expected to describe a real experiment.

The assignment of importance values to a cell is done using an importance store
described below.

An ``importance store'' with the interface G4VIStore is used to store importance
values related to cells. In order to do importance sampling the user has to
create an object (e.g. of class G4IStore) of type G4VIStore. The samplers may be
given a G4VIStore. The user fills the store with cells and their importance
values. The store is now a singleton class so should be created using a
GetInstance method:

重要性采样作用于那些穿过不同"importance cells"的边界的粒子。这个行为依赖于给 cells
指定的重要性值。通常，如果重要性增加或者重要性减小，那么，相应的，这个粒子 history分裂或者被使用俄罗斯轮盘赌。根据相应的行为，这个 history
指定的权重将被改变。

这些为重要性采样提供的工具要求用户对问题的物理过程有很好的理解。这是因为用户需要决定哪个粒子必须被重要性采样，定义 cells 并且给相应的 cells
赋相应的重要性值。如果这些没有被正确的指定，那么不能期望获得描述真实实验的结果。

下面描述了怎样使用 importance store 给一个 cell 指定重要性值。

与接口 G4VIStore 有关的"importance store"被用于存储相关 cells 的重要性值。为了进行重要性采样，用户必须创建一个
G4VIStore 类型(例如， G4IStore 类)的对象 。取样器可以指定一个 G4VIStore。用户使用 cells 和相应的重要性值来填充
importance store。

Importance store 必须使用用于重要性采样的几何体的 world 几何体的引用来构造，可以是mass 几何体或者 parallel 几何体的
world 几何体。 Importance stores 从接口 G4VIStore 派生：

\begin{lstlisting}
G4IStore *aIstore = G4IStore::GetInstance();
\end{lstlisting}

Or if a parallel world is used: 或者如果使用平行世界：

\begin{lstlisting}
G4IStore *aIstore = G4IStore::GetInstance(pdet->GetName());
\end{lstlisting}

An importance store has to be constructed with a reference to the world volume
of the geometry used for importance sampling. This may be the world volume of the
mass or of a parallel geometry. Importance stores derive from the interface
G4VIStore:

重要性store必须参照用于重要性抽样的世界体来构建。 这可能是质量的世界体或平行几何体的世界体。 重要性store从G4VIStore派生：

\begin{lstlisting}
class G4VIStore
{
public:
G4VIStore();
virtual ~G4VIStore();
virtual G4double GetImportance(const G4GeometryCell &gCell) const = 0;
virtual G4bool IsKnown(const G4GeometryCell &gCell) const = 0;
virtual const G4VPhysicalVolume &GetWorldVolume() const = 0;
};
\end{lstlisting}

A concrete implementation of an importance store is provided by the class
G4VStore. The \textit{public }part of the class is:

由类 G4VStore 提供的 importance store 的具体实现。这个类的公有部分

\begin{lstlisting}
class G4IStore : public G4VIStore
{
public:
explicit G4IStore(const G4VPhysicalVolume &worldvolume);
virtual ~G4IStore();
virtual G4double GetImportance(const G4GeometryCell &gCell) const;
virtual G4bool IsKnown(const G4GeometryCell &gCell) const;
virtual const G4VPhysicalVolume &GetWorldVolume() const;
void AddImportanceGeometryCell(G4double importance,
const G4GeometryCell &gCell);
void AddImportanceGeometryCell(G4double importance,
const G4VPhysicalVolume &,
G4int aRepNum = 0);
void ChangeImportance(G4double importance,
const G4GeometryCell &gCell);
void ChangeImportance(G4double importance,
const G4VPhysicalVolume &,
G4int aRepNum = 0);
G4double GetImportance(const G4VPhysicalVolume &,
G4int aRepNum = 0) const ;
private: .....
};
\end{lstlisting}

The member function AddImportanceGeometryCell() enters a cell and an importance
value into the importance store. The importance values may be returned either
according to a physical volume and a replica number or according to a
G4GeometryCell. The user must be aware of the interpretation of assigning
importance values to a cell. If scoring is also implemented then this is attached
to logical volumes, in which case the physical volume and replica number method
should be used for assigning importance values. See examples/extended/biasing B01
and B02 for examples of this.

成员函数 AddImportanceGeometryCell() 将一个 cell 及其重要性值添加到 importance store。根据一个物理体和一个
replica number，或者根据一个 G4GeometryCell，可以获取相应的重要性值。用户必须注意给一个 cell
赋重要性值的阐述。如果还实施了计数，则将其附加到逻辑体，在这种情况下，应使用物理体和副本编号方法分配重要性值。
有关这方面的示例，请参阅examples/extended/biasing B01 and B02。


\rule{\textwidth}{1 pt}
\begin{flushleft}
Note: An importance value must be assigned to every cell.

重要性值必须赋给每一个 cell。

在 G4 中， world 体的 replica number 是 -1。

\end{flushleft}
\rule{\textwidth}{1 pt}

\begin{itemize}
	\item \textit{Cell is not in store}


Not filling a certain cell in the store will cause an exception.

	\item \textit{Importance value = zero}

Tracks of the chosen particle type will be killed.


	\item \textit{importance values $>$ 0 }
	
	Normal allowed values
	\item \textit{Importance value smaller zero }
	
	Not allowed!
\end{itemize}


\begin{itemize}
\item Cell 不在 importance store 中

没有填充某个 cell 到 store 将引起一个异常。

\item 重要性值 =0

相应粒子的径迹将被 kill。

\item 重要性值 $>$ 0，正常允许值

\item 重要性值$<$0，不允许!

\end{itemize}

\paragraph{The Importance Sampling Algorithm【重要性采样算法】}

Importance sampling supports using a customized importance sampling algorithm.
To this end, the sampler interface \textit{Changing the Sampling }may be given a
pointer to the interface G4VImportanceAlgorithm:

重要性采样支持使用用户自定义的重要性采样算法。最后，取样器接口 G4VSampler 将被指定一个指向接口 G4VImportanceAlgorithm
的指针：

\begin{lstlisting}
class G4VImportanceAlgorithm
{
public:
G4VImportanceAlgorithm();
virtual ~G4VImportanceAlgorithm();
virtual G4Nsplit_Weight Calculate(G4double ipre,
G4double ipost,
G4double init_w) const = 0;
};
\end{lstlisting}

The method Calculate() takes the arguments:

\begin{itemize}
	\item \textit{ipre}, \textit{ipost }: importance of the previous cell and theimportance of the current cell, respectively.
	\item \textit{init\_w}: the particle's weight
\end{itemize}

It returns the struct:

方法 Calculate() 使用以下参数：
\begin{itemize}
\item ipre, ipost: 分别是前一个 cell 和当前 cell 的重要性值。
\item init\_w: 粒子权重
\end{itemize}

它返回以下结构：

\begin{lstlisting}
class G4Nsplit_Weight
{
public:
G4int fN;
G4double fW;
};
\end{lstlisting}

\begin{itemize}
	\item \textit{fN}: the calculated number of particles to exit the importance sampling
	\item \textit{fW}: the weight of the particles
\end{itemize}

The user may have a customized algorithm used by providing a class inheriting
from G4VImportanceAlgorithm.

If no customized algorithm is given to the sampler the default importance
sampling algorithm is used. This algorithm is implemented in
G4ImportanceAlgorithm.

\begin{itemize}
	\item \textit{fN}: 到退出重要性采样的时候已计算的粒子数目
	\item \textit{fW}: 粒子权重
\end{itemize}

用户可以通过提供一个从 G4VImportanceAlgorithm 继承的类使用自定义的算法。

如果没有自定义算法指定给取样器，缺省的重要性采样算法将被使用。这个算法在G4ImportanceAlgorithm 中实现。

\paragraph{The Weight Window Technique【权重窗技术】}

The weight window technique is a weight-based alternative to importance
sampling:

权重窗口技术是重要性抽样的基于权重的替代方法：

\begin{itemize}
	\item applies splitting and Russian roulette depending on space (cells) and energy
	\item user defines weight windows in contrast to defining importance values as in importance sampling
\end{itemize}

\begin{itemize}
	\item 根据空间（细胞）和能量进行分裂和俄罗斯轮盘赌
	\item 与重要性抽样一样，用户定义权重窗口与定义重要性值不同
\end{itemize}

In contrast to importance sampling this technique is not weight blind. Instead
the technique is applied according to the particle weight with respect to the
current energy-space cell.

Therefore the technique is convenient to apply in combination with other
variance reduction techniques such as crosssection biasing and implicit capture.

与重要性抽样相比，这种技术不是盲目的。 相反，根据当前能量空间cell的粒子权重应用该技术。

因此，该技术可以方便地与其他方差减少技术结合使用，例如横截面偏置和隐式捕获。

A weight window may be specified for every cell and for several energy regions:
\textit{space-energy cell}.


{\raggedright
Weight window concept
}

The user specifies a \textit{lower weight bound W\_L }for every space-energy
cell.

可以为每个单元和几个能量区域指定权重窗口：空间能量cell。

权重窗口的概念

用户为每个空间能量单元指定较低的权重界限W\_L。

\begin{itemize}
	\item The upper weight bound W\_U and the survival weight W\_S are calculated as:
\end{itemize}

W\_U = C\_U \textit{W\_L }and W\_S = C\_S \textit{W\_L}.

\begin{itemize}
	\item The user specifies C\_S and C\_U once for the whole problem.
	\item The user may give different sets of energy bounds for every cell or one set for
all geometrical cells
	\item Special case: if C\_S = C\_U = 1 for all energies then weight window is
equivalent to importance sampling
	\item The user can choose to apply the technique: at boundaries, on collisions or on
boundaries and collisions
\end{itemize}

\begin{itemize}
\item 权重上限W\_U和生存权重W\_S计算如下：

W\_U = C\_U W\_L和W\_S = C\_S W\_L。

\item 用户为整个问题指定C\_S和C\_U一次。
\item 用户可以为每个单元给予不同的能量边界集，或者为所有几何单元给出一组能量边界
\item 特殊情况：如果所有能量的C\_S = C\_U = 1，则加权窗口相当于重要性采样
\item 用户可以选择应用该技术：边界，碰撞或边界和碰撞
\end{itemize}

The energy-space cells are realized by G4GeometryCell as in importance sampling.
The cells are stored in a weight window store defined by G4VWeightWindowStore:

能量空间单元由重要性采样中的G4GeometryCell实现。 单元存储在由G4VWeightWindowStore定义的加权窗口存储中：

\begin{lstlisting}
class G4VWeightWindowStore {
public:
G4VWeightWindowStore();
virtual ~G4VWeightWindowStore();
virtual G4double GetLowerWeitgh(const G4GeometryCell &gCell,
G4double partEnergy) const = 0;
virtual G4bool IsKnown(const G4GeometryCell &gCell) const = 0;
virtual const G4VPhysicalVolume &GetWorldVolume() const = 0;
};
\end{lstlisting}

\begin{figure}[htpb]
\centering
\includegraphics[width=0.8 \textwidth]{FIG/fig3-2.png}
\caption{权重窗的概念}
\end{figure}

A concrete implementation is provided:

提供了一个具体的实现：

\begin{lstlisting}
class G4WeightWindowStore: public G4VWeightWindowStore {
public:
explicit G4WeightWindowStore(const G4VPhysicalVolume &worldvolume);
virtual ~G4WeightWindowStore();
virtual G4double GetLowerWeitgh(const G4GeometryCell &gCell,
G4double partEnergy) const;
virtual G4bool IsKnown(const G4GeometryCell &gCell) const;
virtual const G4VPhysicalVolume &GetWorldVolume() const;
void AddLowerWeights(const G4GeometryCell &gCell,
const std::vector<G4double> &lowerWeights);
void AddUpperEboundLowerWeightPairs(const G4GeometryCell &gCell,
const G4UpperEnergyToLowerWeightMap&
enWeMap);
void SetGeneralUpperEnergyBounds(const
std::set<G4double, std::less<G4double> > & enBounds);
private::
...
};
\end{lstlisting}

The user may choose equal energy bounds for all cells. In this case a set of
upper energy bounds must be given to the store using the method
SetGeneralUpperEnergyBounds. If a general set of energy bounds have been set
AddLowerWeights can be used to add the cells.

Alternatively, the user may chose different energy regions for different cells.
In this case the user must provide a mapping of upper energy bounds to lower
weight bounds for every cell using the method AddUpperEboundLowerWeightPairs.

Weight window algorithms implementing the interface class
G4VWeightWindowAlgorithm can be used to define a customized algorithm:

用户可以为所有单元选择相等的能量范围。 在这种情况下，必须使用SetGeneralUpperEnergyBounds方法向store提供一组高能量边界。
如果已经设置了一组通用的能量边界，则可以使用AddLowerWeights添加单元格。

或者，用户可以为不同的单元选择不同的能量区域。
在这种情况下，用户必须使用方法AddUpperEboundLowerWeightPairs为每个单元格提供高能量边界映射到较低权重边界。

实现接口类G4VWeightWindowAlgorithm的加权窗口算法可用于定义自定义算法：

\begin{lstlisting}
class G4VWeightWindowAlgorithm {
public:
G4VWeightWindowAlgorithm();
virtual ~G4VWeightWindowAlgorithm();
virtual G4Nsplit_Weight Calculate(G4double init_w,
G4double lowerWeightBound) const = 0;
};
\end{lstlisting}

A concrete implementation is provided and used as a default:

具体实现提供并用作默认值：

\begin{lstlisting}
class G4WeightWindowAlgorithm : public G4VWeightWindowAlgorithm {
public:
G4WeightWindowAlgorithm(G4double upperLimitFaktor = 5,
G4double survivalFaktor = 3,
G4int maxNumberOfSplits = 5);
virtual ~G4WeightWindowAlgorithm();
virtual G4Nsplit_Weight Calculate(G4double init_w,
G4double lowerWeightBound) const;
private:
...
};
\end{lstlisting}

The constructor takes three parameters which are used to: calculate the upper
weight bound (upperLimitFaktor), calculate the survival weight (survivalFaktor),
and introduce a maximal number (maxNumberOfSplits) of copies to be created in one
go.

In addition, the inverse of the maxNumberOfSplits is used to specify the minimum
survival probability in case of Russian roulette.

构造函数接受三个参数：计算上限权重（upperLimitFaktor），计算生存权重（survivalFaktor），并引入要一次创建的副本的最大数量（maxNumberOfSplits）。

此外，maxNumberOfSplits的倒数用于指定俄罗斯轮盘赌时的最低生存概率。


\paragraph{The Weight Roulette Technique【权重轮盘赌技巧】}

Weight roulette (also called weight cutoff) is usually applied if importance
sampling and implicit capture are used together. Implicit capture is not
described here but it is useful to note that this procedure reduces a particle
weight in every collision instead of killing the particle with some probability.

如果重要性采样和隐含俘获被同时使用，那么权重轮盘赌
(也叫权重截断)通常被采用。隐含俘获没有在这里描述，需要注意：隐含俘获在每次碰撞发生的时候，以一定的概率，使用减小粒子权重的办法来代替杀死粒子。

Together with importance sampling the weight of a particle may become so low
that it does not change any result significantly. Hence tracking a very low
weight particle is a waste of computing time. Weight roulette is applied in order
to solve this problem.

与重要性采样一起，粒子权重可以变得很小以致不会显著改变任何结果。所以，跟踪一个非常低权重的粒子意味着浪费计算时间。为了解决这个问题，将使用权重轮盘赌。

{\raggedright
The weight roulette concept【权重轮盘赌概念】
}

Weight roulette takes into account the importance ``Ic'' of the current cell and
the importance ``Is'' of the cell in which the source is located, by using the
ratio ``R=Is/Ic''.

Weight roulette uses a relative minimal weight limit and a relative survival
weight. When a particle falls below the weight limit Russian roulette is applied.
If the particle survives, tracking will be continued and the particle weight will
be set to the survival weight.

The weight roulette uses the following parameters with their default values:

权重轮盘赌必须考虑当前 cell 的重要性"Ic"，和源所在 cell 的重要性，使用他们的比"R=Is/Ic"。

权重轮盘赌使用一个相对最小权重限和一个相对存活权重。当一个粒子掉到低于权重限的时候，将使用俄罗斯轮盘赌。如果粒子存活，
跟踪将继续，并且粒子权重将被设置为存活权重。

权重轮盘赌使用下列参数和他们的缺省值：

\begin{itemize}
	\item \textit{wsurvival}: 0.5
	\item \textit{wlimit}: 0.25
	\item \textit{isource}: 1
\end{itemize}

\noindent The following algorithm is applied: 下列算法被采样：

\noindent If a particle weight ``w'' is lower than R*wlimit:

\noindent 如果粒子权重"w"小于 R*wlimit:

\begin{itemize}
	\item the weight of the particle will be changed to ``ws = wsurvival*R''
	
	粒子权重将被改变为"ws = wsurvival*R"
	\item the probability for the particle to survive is ``p = w/ws''
	
	粒子存活的可能性为"p = w/ws
\end{itemize}


\subsection{Physics Based Biasing【基于物理学的偏置】}

GEANT4 supports physics based biasing through a number of
general use, built in biasing techniques. A utility class, G4WrapperProcess, is
also available to support user defined biasing.

GEANT4支持基于物理的偏置，通过一些通用的偏置技术构建。 实用程序类G4WrapperProcess也可用于支持用户定义的偏差。

{\raggedright
\textbf{Built in Biasing Options【内置偏置选项】}
}

\paragraph{Primary Particle Biasing【一次粒子偏置】}

Primary particle biasing can be used to increase the number of primary particles
generated in a particular phase space region of interest. The weight of the
primary particle is modified as appropriate. A general implementation is provided
through the G4GeneralParticleSource class. It is possible to bias position,
angular and energy distributions.

{\raggedright
G4GeneralParticleSource is a concrete implementation of G4VPrimaryGenerator. To
use, instantiate G4GeneralParticleSource in the G4VUserPrimaryGeneratorAction
class, as demonstrated below.
}

{\raggedright
初级粒子偏置可用于增加在感兴趣的特定空间区域中产生的初级粒子的数量。 初级粒子的权重根据需要进行修改。
通过G4GeneralParticleSource类提供了一个常规实现。 可以偏置位置，角度和能量分布。
}

{\raggedright
G4GeneralParticleSource是G4VPrimaryGenerator的具体实现。
要使用，请在G4VUserPrimaryGeneratorAction类中实例化G4GeneralParticleSource，如下所示。
}

\begin{lstlisting}
MyPrimaryGeneratorAction::MyPrimaryGeneratorAction() {
generator = new G4GeneralParticleSource;
}
void
MyPrimaryGeneratorAction::GeneratePrimaries(G4Event*anEvent){
generator->GeneratePrimaryVertex(anEvent);
}
\end{lstlisting}

The biasing can be configured through interactive commands, as described in
\textit{General Particle Source}. Examples are also distributed with the
GEANT4 distribution in examples/extended/eventgenerator/exgps.

偏置可以通过交互式命令进行配置，如通用粒子源【\textit{General Particle Source}】中所述。 示例还通过示例/ extended /
eventgenerator / exgps中的GEANT4分发进行了分发。

\paragraph{Hadronic Leading Particle Biasing【强子导致的粒子偏置】}

One hadronic leading particle biasing technique is implemented in the
G4HadLeadBias utility. This method keeps only the most important part of the
event, as well as representative tracks of each given particle type. So the track
with the highest energy as well as one of each of Baryon, pi0, mesons and
leptons. As usual, appropriate weights are assigned to the particles. Setting the
SwitchLeadBiasOn environmental variable will activate this utility.

在G4HadLeadBias实用程序中实现了一个强子导致的粒子偏置技术。 该方法只保留事件的最重要部分，以及每个给定粒子类型的代表径迹。
因此，能量最高的径迹之一以及Baryon，pi0，介子和轻子中的每一个。 像往常一样，分配给粒子适当的权重。
设置SwitchLeadBiasOn环境变量将激活此实用程序。

\paragraph{Hadronic Cross Section Biasing【强子横截面偏置】}

Cross section biasing artificially enhances/reduces the cross section of a
process. This may be useful for studying thin layer interactions or thick layer
shielding. The built in hadronic cross section biasing applies to photon
inelastic, electron nuclear and positron nuclear processes.

横截面偏置人为地增强/减小过程的横截面。 这对研究薄层交互作用或厚层屏蔽可能有用。 内置的强子横截面偏置适用于光子非弹性，电子核和正电子核过程。

The biasing is controlled through the BiasCrossSectionByFactor method in
G4HadronicProcess, as demonstrated below.

如下所示，偏置通过G4HadronicProcess中的BiasCrossSectionByFactor方法进行控制。

\begin{lstlisting}
void MyPhysicsList::ConstructProcess()
{
...
G4ElectroNuclearReaction * theElectroReaction =
new G4ElectroNuclearReaction;
G4ElectronNuclearProcess theElectronNuclearProcess;
theElectronNuclearProcess.RegisterMe(theElectroReaction);
theElectronNuclearProcess.BiasCrossSectionByFactor(100);
pManager->AddDiscreteProcess(&theElectronNuclearProcess);
...
}
\end{lstlisting}

\paragraph{Radioactive Decay Biasing【放射性衰减偏置】}

The G4RadioactiveDecay (GRDM) class simulates the decay of radioactive nuclei
and implements the following biasing options:

G4RadioactiveDecay（GRDM）类模拟放射性核的衰变并实现以下偏置选项：

\begin{itemize}
	\item Increase the sampling rate of radionuclides within observation times through a user defined probability distribution function
	
	通过用户定义的概率分布函数提高观察时间内放射性核素的采样率
	\item Nuclear splitting, where the parent nuclide is split into a user defined number of nuclides

核分裂，其中母体核素分裂成用户定义数量的核素
	\item Branching ratio biasing where branching ratios are sampled with equal probability
	
	以相等的概率抽样分支比率时的分支比例偏置
\end{itemize}

G4RadioactiveDecay is a process which must be registered with a process manager,
as demonstrated below.

G4RadioactiveDecay是一个必须在流程管理器中注册的流程，如下所示。

\begin{lstlisting}
void MyPhysicsList::ConstructProcess()
{
...
G4RadioactiveDecay* theRadioactiveDecay =
new G4RadioactiveDecay();
G4ProcessManager* pmanager = ...
pmanager ->AddProcess(theRadioactiveDecay);
...
}
\end{lstlisting}

{\raggedright
Biasing can be controlled either in compiled code or through interactive
commands. Radioactive decay biasing examples are also distributed with the
GEANT4 distribution in examples/extended/radioactivedecay/exrdm.
To select biasing as part of the process registration, use
}

{\raggedright
偏置可以通过编译代码或交互式命令来控制。 放射性衰减偏差示例也在GEANT4分布示例/ extended / radioactivedecay /
exrdm中进行了分发。 要选择偏差作为流程注册的一部分，请使用
}

\begin{lstlisting}
theRadioactiveDecay->SetAnalogueMonteCarlo(false);
\end{lstlisting}

or the equivalent macro command: 或等效的宏命令：

\begin{lstlisting}
/grdm/analogeMC [true|false]
\end{lstlisting}

In both cases, \textit{true }specifies that the unbiased (analogue) simulation
will be done, and \textit{false }selects biasing.

在这两种情况下，true表示将执行无偏（模拟）模拟，false表示偏置。

\paragraph{Limited Radionuclides【有限的放射性核素】}

Radioactive decay may be restricted to only specific nuclides, in order (for
example) to avoid tracking extremely longlived daughters in decay chains which
are not of experimental interest. To limit the range of nuclides decayed as part
of the process registration (above), use

放射性衰变可能仅限于特定的核素，以便（例如）避免跟踪衰变链中长寿命的非兴趣子体。 为了限制作为过程登记（上文）的一部分衰变的核素范围，请使用

\begin{lstlisting}
G4NucleusLimits limits(aMin, aMax, zMin, zMax);
theRadioactiveDecay->SetNucleusLimits(limits);
\end{lstlisting}

or via the macro command  或宏命令：
\begin{lstlisting}
/grdm/nucleusLimits [aMin] [aMax] [zMin] [zMax]
\end{lstlisting}

\paragraph{Geometric Biasing【几何偏置】}

Radioactive decays may be generated throughout the user's detector model, in one
or more specified volumes, or nowhere. The detector geometry must be defined
before applying these geometric biases. Volumes may be selected or deselected
programmatically using

放射性衰变可能贯穿用户的探测器模型，在一个或多个指定的体中或任何地方。 在应用这些几何偏差之前，必须定义探测器的几何形状。 可以使用编程方式选择或取消
volume。

\begin{lstlisting}
theRadioactiveDecay->SelectAllVolumes();
theRadioactiveDecay->DeselectAllVolumes();
G4LogicalVolume* aLogicalVolume;
// Acquired by the user
theRadioactiveDecay->SelectVolume(aLogicalVolume);
theRadioactiveDecay->DeselectVolume(aLogicalVolume);
\end{lstlisting}

or with the equivalent macro commands或等效的宏命令：

\begin{lstlisting}
/grdm/allVolumes
/grdm/noVolumes
/grdm/selectVolume [logicalVolume]
/grdm/deselectVolume [logicalVolume]
\end{lstlisting}

In macro commands, the volumes are specified by name, and found by searching the
G4LogicalVolumeStore.

在宏命令中，volume由名称指定，并通过G4LogicalVolumeStore搜索找到。

\paragraph{Decay Time Biasing【衰变时间的偏差】}

The decay time function (normally an exponential in the natural lifetime) of the
primary particle may be replaced with a \textit{time profile }F(t), as discussed
in Section 40.6 of the \textit{Physics Reference Manual}. The profile function is
represented as a two-column ASCII text file with up to 100 time points (first
column) with fractions (second column).

正如物理参考手册\textit{Physics Reference
Manual}第40.6节所讨论的那样，初级粒子的衰变时间函数（通常是自然寿命的指数）可以用时间分布F（t）来代替。
配置文件功能以两列ASCII文本文件的形式表示，最多有100个时间点（第一列）和分数（第二列）。

\begin{lstlisting}
theRadioactiveDecay->SetSourceTimeProfile(fileName);
theRadioactiveDecay->SetDecayBias(fileName);
\end{lstlisting}

\begin{lstlisting}
/grdm/sourceTimeProfile [fileName]
/grdm/decayBiasProfile [fileName]
\end{lstlisting}

\paragraph{Branching Fraction Biasing【分支分数偏置】}

Radionuclides with rare decay channels may be biased by forcing all channels to
be selected uniformly (BRBias = \textit{true }below), rather than according to
their natural branching fractions (\textit{false}).

具有稀有衰变通道的放射性核素可能会通过强制所有通道被统一选择（BRBias =
true低于）而不是根据它们的自然分支分数（\textit{false}）来偏见。

\begin{lstlisting}
theRadioactiveDecay->SetBRBias(true);
\end{lstlisting}

\begin{lstlisting}
/grdm/BRbias [true|false]
\end{lstlisting}

\paragraph{Nuclear Splitting【核分裂】}

The statistical efficiency of generated events may be increased by generating
multiple ``copies'' of nuclei in an event, each of which is decayed
independently, with an assigned weight of 1/Nsplit. Scoring the results of
tracking the decay daughters, using their corresponding weights, can improve the
statistical reach of a simulation while preserving the shape of the resulting
distributions.

生成的事件的统计效率可以通过在事件中产生多个核的``副本''来增加，其中每个核都独立地衰减，分配的权重为1 / Nsplit。
使用它们相应的权重评分衰变子体的跟踪结果可以提高模拟的统计效果，同时保留所得分布的形状。

\begin{lstlisting}
theRadioactiveDecay->SetSplitNuclei(Nsplit);
\end{lstlisting}

\begin{lstlisting}
/grdm/splitNucleus [Nsplit]
\end{lstlisting}

\paragraph{G4WrapperProcess}

G4WrapperProcess can be used to implement user defined event biasing.
G4WrapperProcess, which is a process itself, wraps an existing process. By
default, all function calls are forwarded to the wrapped process. It is a
non-invasive way to modify the behaviour of an existing process.

G4WrapperProcess可用于实现用户定义的事件偏置。 G4WrapperProcess本身就是一个进程，它包装了一个现有的进程。
默认情况下，所有函数调用都被转发到包装进程。 这是修改现有流程行为的非侵入性方式。

To use this utility, first create a derived class inheriting from
G4WrapperProcess. Override the methods whose behaviour you would like to modify,
for example, PostStepDoIt, and register the derived class in place of the process
to be wrapped. Finally, register the wrapped process with G4WrapperProcess. The
code snippets below demonstrate its use.

要使用此实用程序，请首先创建一个从G4WrapperProcess继承的派生类。
覆盖您想要修改其行为的方法，例如PostStepDoIt，并注册派生类来代替要打包的进程。 最后，用G4WrapperProcess注册包装过程。
下面的代码片段演示了它的用法。

\begin{lstlisting}
class MyWrapperProcess : public G4WrapperProcess {
...
G4VParticleChange* PostStepDoIt(const G4Track& track,
const G4Step& step) {
// Do something interesting
}
};
void MyPhysicsList::ConstructProcess()
{
...
G4eBremsstrahlung* bremProcess =
new G4eBremsstrahlung();
MyWrapperProcess* wrapper = new MyWrapperProcess();
wrapper->RegisterProcess(bremProcess);
processManager->AddProcess(wrapper, -1, -1, 3);
}
\end{lstlisting}


\subsection{3.7.3 Adjoint/Reverse Monte Carlo【伴随/逆向蒙特卡罗】}

Another powerful biasing technique available in GEANT4 is the
Reverse Monte Carlo (RMC) method, also known as the Adjoint Monte Carlo method.
In this method particles are generated on the external boundary of the sensitive
part of the geometry and then are tracked backward in the geometry till they
reach the external source surface, or exceed an energy threshold. By this way the
computing time is focused only on particle tracks that are contributing to the
tallies. The RMC method is much rapid than the Forward MC method when the
sensitive part of the geometry is small compared to the rest of the geometry and
to the external source, that has to be extensive and not beam like. At the moment
the RMC method is implemented in GEANT4 only for some
electromagnetic processes (see \textit{Reverse processes}). An example
illustrating the use of the Reverse MC method in GEANT4 is
distributed within the GEANT4 toolkit in
examples/extended/biasing/ReverseMC01.

GEANT4中另一个强大的偏置技术是Reverse Monte Carlo（RMC）方法，也称为伴随蒙特卡罗方法。
在这种方法中，粒子在几何形状的敏感部分的外部边界上生成，然后在几何体中向后追踪，直到它们到达外部源表面或超过能量阈值。
通过这种方式，计算时间只集中在贡献记录的粒子径迹上。
RMC方法比正向MC方法快得多，当几何形状的敏感部分相对于几何形状的其余部分和外部源而言较小时，该部分必须是广泛的而不是像梁。
目前RMC方法仅在某些电磁过程中在GEANT4中实施（请参阅逆向过程）。 GEANT4中逆向MC方法的使用示例在GEANT4工具包中的examples /
extended / biasing / ReverseMC01中进行了分发。

\paragraph{Treatment of the Reverse MC method in GEANT4【GEANT4中逆向MC方法的处理】}

Different G4Adjoint classes have been implemented into the GEANT4 toolkit in order to run an adjoint/reverse simulation in a GEANT4 application. This implementation is illustrated in Fig. 3.3. An adjoint
run is divided in a series of alternative adjoint and forward tracking of adjoint
and normal particles. One GEANT4 event treats one of this
tracking phase.

GEANT4工具包中实现了不同的G4Adjoint类，以便在GEANT4应用程序中运行伴随/逆向仿真。 这个实现如图\ref{fig:3-3}所示。
伴随运行分为一系列伴随和正常粒子的可选伴随和正向跟踪。 一个GEANT4事件处理这个跟踪阶段之一。

\begin{figure}
\centering
\label{fig:3-3}
\includegraphics[width=0.5 \textwidth]{FIG/fig3-3.png}
\caption{ GEANT4中伴随/逆向模拟的示意图。}
\end{figure}


\paragraph{Adjoint tracking phase【伴随跟踪阶段】}

Adjoint particles (adjoint\_e-, adjoint\_gamma,. . . ) are generated one by one
on the so called adjoint source with random position, energy (1/E distribution)
and direction. The adjoint source is the external surface of a user defined
volume or of a user defined sphere. The adjoint source should contain one or
several sensitive volumes and should be small compared to the entire geometry.
The user can set the minimum and maximum energy of the adjoint source. After its
generation the adjoint primary particle is tracked backward in the geometry till
a user defined external surface (spherical or boundary of a volume) or is killed
before if it reaches a user defined upper energy limit that represents the
maximum energy of the external source. During the reverse tracking, reverse
processes take place where the adjoint particle being tracked can be either
scattered or transformed in another type of adjoint particle. During the reverse
tracking the G4AdjointSimulationManager replaces the user defined primary, run,
stepping, . . . actions, by its own actions. A reverse tracking phase corresponds
to one GEANT4 event.

伴随粒子（adjoint\_e-，adjoint\_gamma，...）在具有随机位置，能量（1 /
E分布）和方向的所谓伴随源上逐一生成。伴随源是用户定义的体或用户定义的球体的外表面。伴随源应该包含一个或多个敏感体，与整个几何体相比应该很小。用户可以设置伴随源的最小和最大能量。在生成之后，如果用户定义的外部表面（球体或体的边界）在用户定义的能量上限（表示外部能源的最大能量）之前被追踪，则会在几何体中向后追踪伴随的初级粒子。在逆向跟踪过程中，逆向过程发生在被跟踪的伴随粒子可以被散射或被转换成另一种类型的伴随粒子的地方。在逆向追踪期间，G4AdjointSimulationManager将替换用户定义的primary,
run, stepping, . . . actions，通过自己的操作。逆向跟踪阶段对应于一个GEANT4事件。

\paragraph{Forward tracking phase【前向跟踪阶段】}

When an adjoint particle reaches the external surface its weight, type,
position, and direction are registered and a normal primary particle, with a type
equivalent to the last generated primary adjoint, is generated with the same
energy, position but opposite direction and is tracked in the forward direction
in the sensitive region as in a forward MC simulation. During this forward
tracking phase the event, stacking, stepping, tracking actions defined by the
user for his forward simulation are used. By this clear separation between
adjoint and forward tracking phases, the code of the user developed for a forward
simulation should be only slightly modified to adapt it for an adjoint simulation
(see \textit{How to update a G4 application to use the reverse Monte Carlo
mode}). Indeed the computation of the signals is done by the same actions or
classes that the one used in the forward simulation mode. A forward tracking
phase corresponds to one G4 event.

当伴随粒子到达外部表面时，其重量，类型，位置和方向被记录下来，并且具有与最后生成的主要伴随物相当的类型的正常初级粒子以相同的能量，位置但方向相反地被生成并且被跟踪
在正向MC模拟中，在敏感区域的正向。 在此正向追踪阶段，使用用户为其正向模拟定义的event, stacking, stepping, tracking
actions事件。
通过伴随跟踪阶段和前向跟踪阶段之间的清晰分离，用户为正向模拟开发的代码应该稍加修改，以适应伴随模拟（请参阅如何更新G4应用程序以使用反向蒙特卡罗模式）。
事实上，信号的计算是通过与在正向模拟模式下使用的相同的动作或类来完成的。 前向跟踪阶段对应于一个G4事件。

\paragraph{Reverse processes【逆向过程】}

During the reverse tracking, reverse processes act on the adjoint particles. The
reverse processes that are at the moment available in GEANT4 are
the:

在逆向跟踪期间，逆向过程作用于伴随粒子。 目前在GEANT4中可用的逆向过程是：

\begin{itemize}
	\item Reverse discrete ionization for e-, proton and ions
	\item Continuous gain of energy by ionization and bremsstrahlung for e- and by
ionization for protons and ions
	\item Reverse discrete e- bremsstrahlung
	\item Reverse photo-electric effect
	\item Reverse Compton scattering
	\item Approximated multiple scattering (see comment in \textit{Reverse multiple
scattering})
\end{itemize}

\begin{itemize}
	\item 电子，质子和离子的逆向离散电离

	\item 通过电离和韧致辐射连续获得电子能量，并通过电离质子和离子获得能量
	\item 逆向离散电子韧致辐射

	\item 逆向光电效应

	\item 逆向康普顿散射
	\item 近似多次散射（请参阅逆向多次散射中的评论）
\end{itemize}


It is important to note that the electromagnetic reverse processes are cut
dependent as their equivalent forward processes. The implementation of the
reverse processes is based on the forward processes implemented in the G4
standard electromagnetic package.

需要注意的是，电磁逆向过程作为其等同的正向过程而被切断。 逆向过程的实施基于G4标准电磁库中实施的正向过程。

\paragraph{Nb of adjoint particle types and nb of G4 events of an adjoint
simulation【伴随粒子类型的Nb和伴随模拟的G4事件的nb】}

The list of type of adjoint and forward particles that are generated on the
adjoint source and considered in the simulation is a function of the adjoint
processes declared in the physics list. For example if only the e- and gamma
electromagnetic processes are considered, only adjoint e- and adjoint gamma will
be considered as primaries. In this case an adjoint event will be divided in four
G4 event consisting in the reverse tracking of an adjoint e-, the forward
tracking of its equivalent forward e-, the reverse tracking of an adjoint gamma,
and the forward tracking of its equivalent forward gamma. In this case a run of
100 adjoint events will consist into 400 GEANT4 events. If the
proton ionization is also considered adjoint and forward protons are also
generated as primaries and 600 GEANT4 events are processed for
100 adjoint events.

在伴随源上生成并在模拟中考虑的伴随粒子和前向粒子的类型是物理列表中声明的伴随过程的函数。 例如，如果仅考虑e-和伽玛电磁过程，则只将伴随e-和伴随伽马视为初级。
在这种情况下，伴随事件将被分成四个G4事件，包括伴随e-的逆向追踪，其等效前向e-的正向追踪，伴随伽马的逆向追踪以及其等效前向的正向伽马追踪。
在这种情况下，100个伴随事件将包含400个GEANT4事件。
如果质子电离也被认为是伴随的，并且前向质子也作为初级产生并且600个GEANT4事件被处理100次伴随事件。

\paragraph{How to update a G4 application to use the reverse Monte Carlo
mode【如何更新G4以使用逆向蒙特卡罗模式】}

Some modifications are needed to an existing GEANT4 application
in order to adapt it for the use of the reverse simulation mode (see also the G4
example examples/extended/biasing/ReverseMC01). It consists into the:

现有的GEANT4应用程序需要进行一些修改，以便使其适用于逆向模拟模式（另请参阅G4示例示例/ extended / biasing /
ReverseMC01）。 它包括：

\begin{itemize}
	\item Creation of the adjoint simulation manager in the main code
	\item Optional declaration of user actions that will be used during the adjoint
tracking phase
	\item Use of a special physics lists that combine the adjoint and forward processes
	\item Modification of the user analysis part of the code
\end{itemize}


\begin{itemize}
	\item 在主代码中创建伴随模拟管理器
	\item 伴随追踪阶段使用用户操作做可选声明
	\item 使用结合伴随和转发过程的特殊物理列表
	\item 修改代码的用户分析部分
\end{itemize}

\paragraph{Creation of G4AdjointSimManager in the
main【在main中创建G4AdjointSimManager】}

The class G4AdjointSimManager represents the manager of an adjoint simulation.
This static class should be created somewhere in the main code. The way to do
that is illustrated below

G4AdjointSimManager类表示伴随模拟的管理器。 这个静态类应该在主代码的某个地方创建。 下面举例说明了这一点


\begin{lstlisting}
int main(int argc,char** argv) {
...
G4AdjointSimManager* theAdjointSimManager = G4AdjointSimManager::GetInstance();
...
}
\end{lstlisting}


By doing this the G4 application can be run in the reverse MC mode as well as in
the forward MC mode. It is important to note that G4AdjointSimManager is not a
new G4RunManager and that the creation of G4RunManager in the main and the
declaration of the geometry, physics list, and user actions to G4RunManager is
still needed. The definition of the adjoint and external sources and the start of
an adjoint simulation can be controlled by G4UI commands in the directory
/adjoint.

通过这样做，G4程序可以在逆向MC模式以及正向MC模式下运行。
值得注意的是，G4AdjointSimManager不是新的G4RunManager，并且仍然需要在主体中创建G4RunManager以及向G4RunManager声明几何，物理列表和用户操作。
伴随和外部源的定义以及伴随模拟的开始可以通过directory /adjoint中的G4UI命令来控制。

\paragraph{Optional declaration of adjoint user actions【伴随用户操作的可选声明】}

During an adjoint simulation the user stepping, tracking, stacking and event
actions declared to G4RunManager are used only during the G4 events dedicated to
the forward tracking of normal particles in the sensitive region, while during
the events where adjoint particles are tracked backward the following happen
concerning these actions:

在伴随模拟期间，向G4RunManager声明的user stepping, tracking,
stacking和事件动作仅在G4事件专用于敏感区域中正常粒子的正向跟踪期间使用，而在向后跟踪伴随粒子的事件期间，会发生以下事件 关于这些行动：

\begin{itemize}
	\item The user stepping action is replaced by G4AdjointSteppingAction that is
responsible to stop an adjoint track when it reaches the external source, exceed the maximum energ  of the external source, or cross the adjoint source surface. If needed the user can declare its own stepping action that will be called by G4AdjointSteppingAction after the check of stopping track conditions. This stepping action can be different that the stepping action used for the forward simulation. It is declared to G4AdjointSimManager by the following lines of code:


用户stepping操作由G4AdjointSteppingAction替代，G4AdjointSteppingAction负责在到达外部源、超过外部源的最大能量或跨过伴随源表面时停止伴随track。
如果需要，用户可以在检查停止跟踪条件后声明其自己的stepping操作，该操作将由G4AdjointSteppingAction调用。
该stepping动作可以与用于正向模拟的stepping动作不同。 它通过以下几行代码向G4AdjointSimManager声明：

\begin{lstlisting}
G4AdjointSimManager* theAdjointSimManager = G4AdjointSimManager::GetInstance();
theAdjointSimManager->SetAdjointSteppingAction(aUserDefinedSteppingAction);
\end{lstlisting}

\item  No stacking, tracking and event actions are considered by default. If needed the user can declare to G4AdjointSimManager stacking, tracking and event actions that will be used only during the adjoint tracking phase. The following lines of code show how to declare these adjoint actions to G4AdjointSimManager:

默认情况下不会考虑堆叠，跟踪和事件操作。 如果需要，用户可以声明G4AdjointSimManager堆栈，跟踪和事件操作，这些操作仅在伴随跟踪阶段使用。
以下几行代码显示了如何将这些伴随操作声明为G4AdjointSimManager：

\begin{lstlisting}
G4AdjointSimManager* theAdjointSimManager = G4AdjointSimManager::GetInstance();
theAdjointSimManager->SetAdjointEventAction(aUserDefinedEventAction);
theAdjointSimManager->SetAdjointStackingAction(aUserDefinedStackingAction);
theAdjointSimManager->SetAdjointTrackingAction(aUserDefinedTrackingAction);
\end{lstlisting}
\end{itemize}

By default no user run action is considered in an adjoint simulation but if
needed such action can be declared to G4AdjointSimManager as such:

默认情况下，在伴随模拟中不考虑用户运行动作，但如果需要，可以向G4AdjointSimManager声明这样的动作：

\begin{lstlisting}
G4AdjointSimManager* theAdjointSimManager = G4AdjointSimManager::GetInstance();
theAdjointSimManager->SetAdjointRunAction(aUserDefinedRunAction);
\end{lstlisting}

\paragraph{Physics list for reverse and forward electromagnetic
processes【逆向和正向电磁过程的物理列表】}

To run an adjoint simulation a specific physics list should be used where
existing G4 adjoint electromagnetic processes and their forward equivalent have
to be declared. An example of such physics list is provided by the class
G4AdjointPhysicsLits in the G4 example extended/biasing/ReverseMC01.

要运行伴随模拟，应在现有G4伴随电磁过程及其前向等价物必须声明的地方使用特定物理列表。 G4示例扩展/偏置/
ReverseMC01中的类G4AdjointPhysicsLits提供了这种物理列表的一个示例。

\paragraph{Modification in the analysis part of the code【修改代码的分析部分】}

The user code should be modified to normalize the signals computed during the
forward tracking phase to the weight of the last adjoint particle that reaches
the external surface. This weight represents the statistical weight that the last
full adjoint tracks (from the adjoint source to the external source) would have
in a forward simulation. If multiplied by a signal and registered in function of
energy and/or direction the simulation results will give an answer matrix of this
signal. To normalize it to a given spectrum it has to be furthermore multiplied
by a directional differential flux corresponding to this spectrum The weight,
direction, position , kinetic energy and type of the last adjoint particle that
reaches the external source, and that would represents the primary of a forward
simulation, can be gotten from G4AdjointSimManager by using for example the
following line of codes

应该修改用户代码以将在正向跟踪阶段计算的信号归一化为最后一个伴随粒子到达外表面的权重。这个权重表示最后一个完整伴随径迹（从伴随源到外部源）在正向模拟中具有的统计权重。如果乘以信号并在能量和/或方向的函数中进行登记，则仿真结果将给出该信号的答案。为了将其标准化为给定的光谱，它必须进一步乘以对应于该光谱的方向微分通量。到达外部源的最后一个伴随粒子的重量，方向，位置，动能和类型，并且这将代表初级可以通过使用下面的代码行从G4AdjointSimManager中获得

\begin{lstlisting}
G4AdjointSimManager* theAdjointSimManager = G4AdjointSimManager::GetInstance();
G4String particle_name = theAdjointSimManager->GetFwdParticleNameAtEndOfLastAdjointTrack();
G4int PDGEncoding= theAdjointSimManager->GetFwdParticlePDGEncodingAtEndOfLastAdjointTrack();
G4double weight = theAdjointSimManager->GetWeightAtEndOfLastAdjointTrack();
G4double Ekin = theAdjointSimManager->GetEkinAtEndOfLastAdjointTrack();
G4double Ekin_per_nuc=theAdjointSimManager->GetEkinNucAtEndOfLastAdjointTrack(); // for ions
G4ThreeVector dir = theAdjointSimManager->GetDirectionAtEndOfLastAdjointTrack();
G4ThreeVector pos = theAdjointSimManager->GetPositionAtEndOfLastAdjointTrack();
\end{lstlisting}

In order to have a code working for both forward and adjoint simulation mode,
the extra code needed in user actions or analysis manager for the adjoint
simulation mode can be separated to the code needed only for the normal forward
simulation by using the following public method of G4AdjointSimManager:

为了使代码能够用于前向模拟和伴随模拟模式，用户动作或分析管理器所需的附加模拟模式所需的额外代码可以通过使用以下公共方法G4AdjointSimManager：

\begin{lstlisting}
G4bool GetAdjointSimMode();
\end{lstlisting}

that returns true if an adjoint simulation is running and false if not.

The following code example shows how to normalize a detector signal and compute
an answer matrix in the case of an adjoint simulation.

如果伴随模拟正在运行，则返回true，否则返回false。

以下代码示例显示了如何在伴随模拟的情况下归一化探测器信号并计算答案矩阵。

\begin{lstlisting}[caption=在伴随模拟情况下的标准化。 在正向跟踪阶段期间计算的检测器信号S被函数F给出的差分方向通量归一化为主要电子源。]
G4double S = ...; // signal in the sensitive volume computed during a forward tracking phase
//Normalization of the signal for an adjoint simulation
G4AdjointSimManager* theAdjSimManager = G4AdjointSimManager::GetInstance();
if (theAdjSimManager->GetAdjointSimMode()) {
G4double normalized_S=0.;
//normalized to a given e- primary spectrum
G4double S_for_answer_matrix=0.; //for e- answer matrix
if (theAdjSimManager->GetFwdParticleNameAtEndOfLastAdjointTrack() == "e-") {
G4double ekin_prim = theAdjSimManager->GetEkinAtEndOfLastAdjointTrack();
G4ThreeVector dir_prim = theAdjointSimManager->GetDirectionAtEndOfLastAdjointTrack();
G4double weight_prim = theAdjSimManager->GetWeightAtEndOfLastAdjointTrack();
S_for_answer_matrix = S*weight_prim;
normalized_S = S_for_answer_matrix*F(ekin_prim,dir);
// F(ekin_prim,dir_prim) gives the differential directional flux of primary e-
}
//follows the code where normalized_S and S_for_answer_matrix are registered or whatever
....
}
//analysis/normalization code for forward simulation
else {
....
}
....
\end{lstlisting}


\paragraph{Control of an adjoint simulation【控制伴随模拟】}

The G4UI commands in the directory /adjoint. allow the user to : 目录/
adjoint中的G4UI命令。 允许用户：

\begin{itemize}
	\item Define the adjoint source where adjoint primaries are generated
	
	定义生成伴随初始的伴随源
	\item Define the external source till which adjoint particles are tracked
	
	定义外部源，直到跟踪哪些伴随粒子
	\item Start an adjoint simulation
	
	开始伴随模拟
\end{itemize}


{\raggedright
\textbf{Known issues in the Reverse MC mode【Reverse MC模式中的已知问题】}
}

\paragraph{Occasional wrong high weight in the adjoint
simulation【在伴随模拟中偶尔错误的高权重】}

In rare cases an adjoint track may get a wrong high weight when reaching the
external source. While this happens not often it may corrupt the simulation
results significantly. This happens in some tracks where both reverse
photo-electric and bremsstrahlung processes take place at low energy. We still
need some investigations to remove this problem at the level of physical
adjoint/reverse processes. However this problem can be solved at the level of
event actions or analysis in the user code by adding a test on the normalized
signal during an adjoint simulation. An example of such test has been implemented
in the GEANT4 example extended/biasing/ReverseMC01. In this
implementation an event is rejected when the relative error of the computed
normalized energy deposited increases during one event by more than 50\% while
the computed precision is already below 10\%.

在极少数情况下，伴随径迹在到达外部源时可能会产生错误的高权重。 虽然这种情况不常发生，但可能会严重破坏模拟结果。
这种情况发生在一些径迹上，其中反向光电和韧致辐射过程均以低能量进行。 我们仍然需要一些调查来消除物理伴随/逆向过程中的这个问题。
然而，这个问题可以通过在伴随模拟期间在归一化信号上添加测试来在事件动作或用户代码中的分析级别解决。 在GEANT4示例扩展/偏置/
ReverseMC01中已经实现了此类测试的一个示例。
在此实现中，当计算的归一化能量的相对误差在一个事件期间增加超过50％而计算的精度已经低于10％时，则拒绝该事件。

\paragraph{Reverse bremsstrahlung【反向韧致辐射】}

A difference between the differential cross sections used in the adjoint and
forward bremsstrahlung models is the source of a higher flux of $>$100 keV gamma
in the reverse simulation compared to the forward simulation mode. In principle
the adjoint processes/models should make use of the direct differential cross
section to sample the adjoint secondaries and compute the adjoint cross section.
However due to the way the effective differential cross section is considered in
the forward model G4eBremsstrahlungModel this was not possible to achieve for the
reverse bremsstrahlung. Indeed the differential cross section used in
G4AdjointeBremstrahlungModel is obtained by the numerical derivation over the cut
energy of the direct cross section provided by G4eBremsstrahlungModel. This would
be a correct procedure if the distribution of secondary in G4eBremsstrahlungModel
would match this differential cross section. Unfortunately it is not the case as
independent parameterization are used in G4eBremsstrahlungModel for both the
cross sections and the sampling of secondaries. (It means that in the forward
case if one would integrate the effective differential cross section considered
in the simulation we would not find back the used cross section). In the future
we plan to correct this problem by using an extra weight correction factor after
the occurrence of a reverse bremsstrahlung. This weight factor should be the
ratio between the differential CS used in the adjoint simulation and the one
effectively used in the forward processes. As it is impossible to have a simple
and direct access to the forward differential CS in G4eBremsstrahlungModel we are
investigating the feasibility to use the differential CS considered in G4Penelope
models.

与前向模拟模式相比，反向模拟中伴随和前向韧致辐射模型中使用的微分截面之间的差异是更高通量$>$
100keV伽马的来源。原则上，伴随过程/模型应该使用直接微分截面来对伴随次级样品进行采样并且计算伴随截面。然而，由于在正向模型G4eBremsstrahlungModel中考虑有效微分截面的方式，这对于反向韧致辐射是不可能实现的。事实上，G4AdjinteBremstrahlungModel中使用的微分截面是通过对由G4eBremsstrahlungModel提供的直接截面的截断能量的数值推导获得的。如果G4eBremsstrahlungModel中的次级分布匹配这个微分截面，这将是一个正确的过程。不幸的是，在G4eBremsstrahlungModel中，对于横截面和次级采样都使用独立参数化。
（这意味着在前向情况下，如果将模拟中考虑的有效微分截面积分，我们不会找回使用的截面）。在未来，我们计划通过在发生反向韧致辐射后使用额外的权重校正因子来纠正这个问题。该权重因子应该是伴随模拟中使用的差分CS与正向过程中有效使用的差分CS之间的比率。由于在G4eBremsstrahlungModel中无法简单直接地访问前向差分CS，因此我们正在研究使用G4Penelope模型中考虑的差分CS的可行性。

\paragraph{Reverse multiple scattering【反向多重散射】}

For the reverse multiple scattering the same model is used than in the forward
case. This approximation makes that the discrepancy between the adjoint and
forward simulation cases can get to a level of \textasciitilde{} 10-15\% relative
differences in the test cases that we have considered. In the future we plan to
improve the adjoint multiple scattering models by forcing the computation of
multiple scattering effect at the end of an adjoint step.

对于反向多重散射，使用相同的模型而不是前向的情况。 这种近似使得伴随模拟和正向模拟情况之间的差异可以达到我们已经考虑过的测试案例的相对差异约10-15％的水平。
在未来，我们计划通过强制在伴随步骤结束时计算多重散射效应来改善伴随多重散射模型。


\subsection{Generic Biasing【通用偏置】}

The generic biasing scheme provides facilities for:

通用偏置方案提供了以下功能：

\begin{itemize}
	\item physics-based biasing, to alter the behavior of existing physics processes:
	
	基于物理学的偏差，改变现有物理过程的行为：

\begin{itemize}
	\item biasing of physics process interaction occurrence,
	
	物理过程交互发生的偏置，
	\item biasing of physics process final state production;
	
	物理过程最终状态生产的偏向;
\end{itemize}

\item non-physics-based biasing, to introduce or remove particles in the simulation but without affecting the existing physics processes, with techniques like, but not limited to

基于非物理学的偏置，在模拟中引入或移除粒子，但不影响现有的物理过程，技术包括但不限于
\begin{itemize}
	\item splitting,
	
	分裂，
	\item Russian roulette (killing).
	
	 俄罗斯轮盘赌（杀害）。
\end{itemize}
\end{itemize}

Decisions on what techniques to apply are taken on a step by step and inter-step
basis, hence providing a lot of flexibility.

The scheme has been introduced in 10.0, with new features and some non-backward
compatible changes introduced in 10.1 and 10.2; these are documented in
\textit{Changes from 10.0 to 10.1 }and \textit{Changes from 10.1 to 10.2}.
Parallel geometry capability has been introduced in 10.3.

决定应用什么技术是a step by step和inter-step的基础，因此提供了很大的灵活性。

该方案已在10.0中引入，其中10.1和10.2引入了新功能和一些非后向兼容更改; 这些记录在从10.0到10.1的变化和从10.1到10.2的变化中。
并行几何功能已在10.3中引入。

\paragraph{Overview【概要】}

The generic biasing scheme relies on two abstract classes, that are meant to
model the biasing problems. You have to inherit from them to create your own
concrete classes, or use some of the concrete instances provided (see
\textit{Existing biasing operations, operator and interaction laws}), if they
respond to your case. A dedicated process provides the interface between these
biasing classes and the tracking. In case of parallel geometry usage, an other
process handles the navigation in these geometries.

通用的偏置方案依赖于两个抽象类，这些抽象类意在模拟偏置问题。
您必须从他们身上继承来创建您自己的具体类，或者使用提供的一些具体实例（请参阅现有的偏置操作，操作员和交互法），以便他们对您的例子做出回应。
专用流程提供了这些偏好类和跟踪之间的接口。 在平行几何使用情况下，其他进程处理这些几何中的导航。

The two abstract classes are: 这两个抽象类是：

\begin{itemize}
	\item G4VBiasingOperation: which represents a simple, or ``atomic'' biasing operation,
like changing a process interaction occurrence probability, or changing its final
state production, or making a splitting operation, etc. For the occurrence
biasing case, the biasing is handled with an other class,
``G4VBiasingInteractionLaw``, which holds the properties of the biased
interaction law. An object of this class type must be provided by the occurrence
biasing operation returned.

G4VBiasingOperation：表示简单的或``原子''的偏置操作，如改变过程交互发生概率，或改变其最终状态生产，或进行分割操作等。对于发生偏置情况，偏置用其他类，'G4VBiasingInteractionLaw''，它具有偏向交互法则的特性。 此类类型的对象必须由返回的事件偏移操作提供。
	\item G4VBiasingOperator: which purpose is to make decisions on the above biasing
operations to be applied. It is attached to a G4LogicalVolume and is the pilot of
the biasing in this volume. An operator may decide to delegate to other
operators. An operator acts only in the G4LogicalVolume it is attached to. In
volumes with no biasing operator attached, the usual tracking is applied.

G4VBiasingOperator：其目的是决定应用上述偏置操作。
它附加到G4LogicalVolume上，并且是本书中偏向的试点。 一个操作者可能决定委托给其他操作者。
一个操作者仅在它所连接的G4LogicalVolume中起作用。 在没有附加偏置操作符的volume中，通常会应用跟踪。

\end{itemize}

The process acting as interface between the biasing classes and the tracking is:

作为偏好类和跟踪之间的接口的过程是：

\begin{itemize}
	\item G4BiasingProcessInterface: it is a concrete G4VProcess implementation. It
interrogates the current biasing operator, if any, for biasing operations to be
applied. The G4BiasingProcessInterface can either:

\begin{itemize}
	\item hold a physics process that it wraps and controls: in this case it asks the
operator for physics-based biasing operations (only) to be applied to the wrapped
process,
	\item not hold a physics process: in this case it asks the operator for
non-physics-based biasing operations (only): splitting, killing, etc.
\end{itemize}
	\item The G4BiasingProcessInterface class provides many information that can be used
by the biasing operator. Each G4BiasingProcessInterface provides its identity to
the biasing operator it calls, so that the operator has this information but also
information of the underneath wrapped physics process, if it is the case.


The G4BiasingProcessInterface can be asked for all other
G4BiasingProcessInterface instances at play on the current track. In particular,
this allows the operator to get all cross-sections at the current point (feature
available since 10.1). The code is organized in such a way that these
cross-sections are all available at the first call to the operator in the current
step.

	\item To make G4BiasingProcessInterface instances wrapping physics processes, or to
insert instances not holding a physics process, the physics list has to be
modified -the generic biasing approach is hence invasive to the physics list-.
The way to configure your physics list and related helper tools are described
below.
\end{itemize}

\begin{itemize}
\item G4BiasingProcessInterface：它是一个具体的G4VProcess实现。它询问当前的偏置操作符（如果有的话）以进行偏置操作。
G4BiasingProcessInterface可以：
\begin{itemize}

\item hold一个物理过程，它包裹和控制：在这种情况下，它会要求操作员将基于物理学的偏置操作（仅）应用于包装过程，

\item 不 hold物理过程：在这种情况下，它会要求操作员进行基于非物理学的偏置操作（仅限于）：拆分，查杀等。
\end{itemize}

	\item G4BiasingProcessInterface类提供了可供偏置操作员使用的许多信息。每个G4BiasingProcessInterface都会为其调用的偏移操作符提供它的标识，以便操作员获得这些信息，但如果是这种情况，还会提供底层包装物理过程的信息。
	可以要求G4BiasingProcessInterface在当前径迹上提供所有其他G4BiasingProcessInterface实例。这使操作员可以获得当前点的所有横截面（自10.1起可用的功能）。代码的组织方式使得这些横截面在当前step的第一次呼叫中可用。
	\item 要使G4BiasingProcessInterface实例包装物理过程，或插入不包含物理过程的实例，必须修改物理列表 -一般的偏置方法因此侵入物理列表。下面介绍配置物理列表和相关帮助工具的方法。
\end{itemize}

The process handling parallel geometries is:

处理并行几何的过程是：

\begin{itemize}
	\item G4ParallelGeometriesLimiterProcess, it is a concrete G4VProcess implementation,
which takes care of limiting the step on the boundaries of parallel geometries.
	\item A single instance of G4ParallelGeometriesLimiterProcess handles all parallel
geometries to be considered for a particle type. It collects these geometries by
means of myLimiterProcess-$>$AddParallelWorld("myParallelGeometry") calls.


Given such a process is attached to a particle type, parallel geometries are
hence specified per particle type.


	\item Attaching an instance of this process to a given particle type, and specifying
the parallel geometries to be considered is eased by the helper tools as
explained below.
\end{itemize}

\vspace{2cm}

\begin{itemize}
	\item G4ParallelGeometriesLimiterProcess，它是一个具体的G4VProcess实现，它负责限制平行几何的边界上的step。
	\item G4ParallelGeometriesLimiterProcess的单个实例处理要针对粒子类型考虑的所有平行几何。
它通过调用myLimiterProcess-$>$ AddParallelWorld（``myParallelGeometry''）收集这些几何。
	
	鉴于这样一个过程被附加到一个粒子类型，平行几何因此指定为每个粒子类型。
	\item 将此过程的实例附加到给定的粒子类型，并指定要考虑的平行几何体可以通过辅助工具简化，如下所述。
\end{itemize}

{\subsection*{Getting Started【初始入门】}
}

\paragraph{Examples【例子】}

Six ``Generic Biasing (GB)'' examples are proposed (they have been introduced in
10.0, 10.1 and 10.3, two examples each time):

\begin{itemize}
	\item examples/extended/biasing/GB01:

\begin{itemize}
	\item which shows how biasing of process cross-section can be done.
	
	它展示了如何完成过程横截面的偏置。
	\item This example uses the physics-based biasing operation G4BOptnChangeCrossSection
defined in geant4/source/processes/biasing/generic. This operation performs the
actual process cross-section change. In the example a first G4VBiasingOperator,
GB01BOptrChangeCrossSection, configures and selects this operation. This operator
applies to only one particle type.

此示例使用geant4 / source / processes / biasing /
generic中定义的基于物理学的偏置操作G4BOptnChangeCrossSection。 该操作更改了实际过程横截面。
在该示例中，第一个G4VBiasingOperator（GB01BOptrChangeCrossSection）配置并选择此操作。 此运算符仅适用于一种粒子类型。
	\item To allow several particle types to be biased, a second G4VBiasingOperator,
GB01BOptrMultiParticleChangeCrossSection, is implemented, and which holds a
GB01BOptrChangeCrossSection operator for each particle type to be biased. This
second operator then delegates to the first one the handling of the biasing
operations.

为了允许多种粒子类型被偏置，第二个G4VBiasingOperator，GB01BOptrMultiParticleChangeCrossSection被实现，并且它为每个要偏置的粒子类型保存GB01BOptrChangeCrossSection运算符。
第二个操作员然后委托第一个处理偏置操作。
\end{itemize}
	\item examples/extended/biasing/GB02:

\begin{itemize}
	\item which shows how a ``force collision'' scheme very close to the MCNP one can be
activated.

它显示了如何激活一个非常接近MCNP的``强制碰撞''方案。
	\item This second example has a quite similar approach than the GB01 one, with a
G4VBiasingOperator, QGB02BOptrMultiParticleForceCollision, that holds as many
operators than particle types to be biased, this operators being of
G4BOptrForceCollision type.

第二个例子与GB01的方法非常类似，使用G4VBiasingOperator（QGB02BOptrMultiParticleForceCollision），它拥有与要偏向的粒子类型相同的运算符，该运算符为G4BOptrForceCollision类型。
	\item This G4BOptrForceCollision operator is defined in source/processes/biasing/
generic. It combines several biasing operations to build-up the needed logic (see
\textit{Setting up the application}). It can be in particular looked at to see
how it collects and makes use of physics process crosssections.
这个G4BOptrForceCollision操作符在源/过程/偏置/通用中定义。 它结合了多个偏置操作来构建所需的逻辑（请参阅设置应用程序）。可以特别关注它是如何收集和利用物理过程横截面的。


\end{itemize}
	\item examples/extended/biasing/GB03:

\begin{itemize}
	\item which implements a kind of importance geometry biasing, using the generic
biasing classes.

使用通用的偏置类实现一种重要性几何偏置。
	\item The example uses a simple sampling calorimeter. On the boundary of the absorber
parts, it does splitting (killing) if the track is moving forward (backward). As
the splitting can be too strong in some cases, falling into an over-splitting
situation, even with a splitting by a factor 2, a technique is introduced to
alleviate the problem : a probability to apply the splitting (killing) is
introduced, and with proper tuning of this probability, the over-splitting can be
avoided.

这个例子使用了一个简单的采样量热器。 在吸收器部件的边界上，如果径迹向前（向后）移动，它会分裂（杀死）。
由于分裂在某些情况下可能过于强大，即使在分裂因素2的情况下也会陷入过度分裂的情况，引入了一种技术来缓解该问题：引入应用分裂（杀死）的概率，并且
通过适当调整这个概率，可以避免过度分裂。

\end{itemize}
	\item examples/extended/biasing/GB04:

\begin{itemize}
	\item which implements a bremsstrahlung splitting. Bremsstrahlung splitting exists in
the EM package. In the present example, it is shown how to implement a similar
technique, using the generic biasing classes.

实现韧致分裂。 EM包装中存在韧致辐射分裂。 在本示例中，演示了如何使用通用偏置类来实现类似的技术。
	\item A biasing operator, GB04BOptrBremSplitting, sends a final state biasing
operation, GB04BOptnBremSplitting, for the bremsstrahlung process. Splitting
factor, and options to control the biasing are available through command line.

偏置操作符GB04BOptrBremSplitting发送最终状态偏置操作GB04BOptnBremSplitting用于韧致辐射过程。
分裂因子和控制偏差的选项可通过命令行获得。

\end{itemize}
	\item examples/extended/biasing/GB05:

\begin{itemize}
	\item which illustrates a technique that uses physics cross-sections to determine the
splitting[killing] rate in a shielding problem, it is applied to neutrons. This
technique is supposed to be an invention, to illustrate a technique combining
physics-based information with splitting/killing.

这说明了一种技术，该技术使用物理截面来确定屏蔽问题中的分裂[杀伤]速率，并将其应用于中子。这项技术被认为是一项发明，用来说明将物理信息与分裂/杀伤相结合的技术。
	\item In the classical treatment of the shielding problem, the shield is divided in
slices at the boundaries of which particles are splitted[killed] if moving
forward[backward]. In the present technique, we collect the crosssections of
``absorbing/destroying'' processes : decay, capture, inelastic. We then use the
generic biasing facilities to create an equivalent of a splitting process, that
has a ``cross-section'' which is the sum of the previous ones. This process is
competing with other processes, as a regular one. When this process wins the
competition, it splits the track, with a splitting factor 2. This splitting is
hence occurring at the same rate than the absorption, resulting in an expected
maintained (unweighted) flux.

在屏蔽问题的经典处理中，如果向前[向后]移动，则屏蔽是在边界处粒子被分裂[杀死]的边界。在本技术中，我们收集``吸收/破坏''过程的横截面：衰减，捕获，非弹性。然后，我们使用通用的偏置来创建一个等价的分割过程，它具有一个``横截面''，它是以前的总和。这个过程像其他过程一样，是一个常规过程。当这个过程赢得竞争时，它分裂径迹，分裂因子2.因此这个分裂以与吸收相同的速率发生，导致预期的维持（未加权）通量。
	\item GB05BOptrSplitAndKillByCrossSection and GB05BOptnSplitAndKillByCrossSection are
respectively the biasing operator and operation. The operator collects the
absorbing cross-sections at the beginning of the step, passes them to the
operation, requests it to sample the distance to its next interaction, and
returns this operation to the calling G4BiasingProcessInterface as the operation
to be applied in the step.

GB05BOpSpSplitAndKillByCrossSection和GB05BOptnSplitAndKillByCrossSection分别是偏置操作符和操作。操作员在步骤开始时收集吸收横截面，将它们传递给操作，请求它采样到下一个交互的距离，然后将此操作返回到调用的G4BiasingProcessInterface作为要在步骤中应用的操作。
	\item The operation interaction distance is then proposed by the calling
G4BiasingProcessInterface and, if being the shortest of the interaction
distances, the operation final state generation (the splitting) is applied by the
process.

然后通过调用G4BiasingProcessInterface提出操作交互距离，并且如果交互距离最短，则操作最终状态生成（分割）由过程应用
\end{itemize}
	\item examples/extended/biasing/GB06:

\begin{itemize}
	\item which demonstrates the use of parallel geometries in generic biasing, on a
classical shield problem, using geometry-based importance biasing.

它演示了在通用偏置中使用平行几何，在经典的屏蔽问题上，使用基于几何的重要性偏置。
	\item The mass geometry consists of a single block of concrete; it is overlayed by a
parallel geometry defining the slices used for splitting/killing.

质量几何由一块混凝土组成; 它被定义用于分割/结束的切片的平行几何体覆盖。
	\item The navigation capability in the parallel geometry is activated in the main
program, by means of the physics list constructor.

平行几何中的导航功能通过物理列表构造函数在主程序中激活。

\end{itemize}
\end{itemize}


\paragraph{Setting up the application【设置应用程序】}

For making an existing G4VBiasingOperator used by your application, you have to
do two things:

为了制作应用程序使用的现有G4VBiasingOperator，您必须做两件事：

\begin{enumerate}
	\item Attach the operator to the G4LogicalVolume where the biasing should take place:
You have to make this attachment in your ConstructSDandField() method (to make
your application both sequential and MTcompliant):

\begin{lstlisting}%[caption=Attachment of a G4BiasingOperator to a G4LogicalVolume. We assume such a volume has been created with name ``volumeWithBiasing'', and we assume that a biasing operator class MyBiasingOperator has been created, inheriting from G4VBiasingOperator:]
// Fetch the logical volume pointer by name (it is an example, not a mandatory way):
G4LogicalVolume* biasingVolume = G4LogicalVolumeStore::GetInstance()->GetVolume(
˓ → "volumeWithBiasing");
// Create the biasing operator:
MyBiasingOperator* myBiasingOperator = new MyBiasingOperator("ExampleOperator");
// Attach it to the volume:
myBiasingOperator->AttachTo(biasingVolume);
\end{lstlisting}

\item Setup the physics list you use to properly include the needed
G4BiasingProcessInterface instances. You have several options for this.

设置您用来正确包含所需G4BiasingProcessInterface实例的物理列表。你有几个选择。

	\item The easiest way is if you use a pre-packaged physics list (e.g. FTFP\_BERT,
QGSP. . . ). As such a physics list is of G4VModularPhysicsList type, you can
alter it with a G4VPhysicsConstructor. The constructor G4GenericBiasingPhysics is
meant for this. It can be used, typically in your main program, as:

最简单的方法是，如果您使用预打包物理列表（例如FTFP\_BERT，QGSP ...）。
由于这种物理列表是G4VModularPhysicsList类型，因此可以使用G4VPhysicsConstructor对其进行更改。
构造函数G4GenericBiasingPhysics是为了这个。 通常可以在主程序中使用它，如下所示：


\begin{lstlisting}[caption=使用G4GenericBiasingPhysics物理构造函数来设置预打包物理列表（G4VModularPhysicsList类型）。这里我们假设FTFP\_BERT物理列表，并假设runManager是创建的G4RunManager或G4RMTunManager对象的指针。]
// Fetch the logical volume pointer by name (it is an example, not a mandatory way):
G4LogicalVolume* biasingVolume = G4LogicalVolumeStore::GetInstance()->GetVolume(
˓ → "volumeWithBiasing");
// Create the biasing operator:
MyBiasingOperator* myBiasingOperator = new MyBiasingOperator("ExampleOperator");
// Attach it to the volume:
myBiasingOperator->AttachTo(biasingVolume);
\end{lstlisting}

Doing so, all physics processes will be wrapped, and, for example, the gamma
conversion process,

"conv", will appear as "biasWrapper(conv)" when dumping the processes
(/particle/ process/dump). An additional "biasWrapper(0)" process, for
non-physics-based biasing is also inserted.

Other methods to specifically chose some physics processes to be biased or to insert only
G4BiasingProcessInterface instances for non-physics-based biasing also exist.

这样做，所有的物理过程都将被打包，例如伽马转换过程，``conv''在转储过程（/ particle / process /
dump）时将显示为``biasWrapper（conv）''。还插入了一个额外的``biasWrapper（0）''过程，用于非基于物理学的偏置。

其他的方法来特别选择了一些物理过程被偏置或插入用于非基于物理学的偏置的G4BiasingProcessInterface实例也存在。

\item The second way is useful if you write your own physics list, and if this one is not a modular physics list, but inherits directly from the lowest level abstract class G4VUserPhysicsList. In this case, the above solution with G4GenericBiasingPhysics does not apply. Instead you can use the G4BiasingHelper utility class (this one is indeed used by G4GenericBiasingPhysics).

如果您编写自己的物理列表，并且该列表不是模块物理列表，而是直接从最低级别的抽象类G4VUserPhysicsList继承，则第二种方法非常有用。在这种情况下，使用G4GenericBiasingPhysics的上述解决方案不适用。相反，您可以使用G4BiasingHelper实用程序类（这个实际上由G4GenericBiasingPhysics使用）。
%Use of the G4BiasingHelper utility class to setup a physics list for biasing in case this physics list is not of G4VModularPhysicsList type but inherits directly from G4VUserPhysicsList.
\begin{lstlisting}[caption=Use of the G4GenericBiasingPhysics physics constructor to setup a pre-packaged physics list (of G4VModularPhysicsList type). ]
// Fetch the logical volume pointer by name (it is an example, not a mandatory way):
G4LogicalVolume* biasingVolume = G4LogicalVolumeStore::GetInstance()->GetVolume(
˓ → "volumeWithBiasing");
// Create the biasing operator:
MyBiasingOperator* myBiasingOperator = new MyBiasingOperator("ExampleOperator");
// Attach it to the volume:
myBiasingOperator->AttachTo(biasingVolume);
\end{lstlisting}
程序清单3.8：使用G4BiasingHelper实用程序类来设置偏置的物理列表，以防此物理列表不是G4VModularPhysicsList类型，而是直接从G4VUserPhysicsList继承。
\begin{lstlisting}[caption=Use of the G4BiasingHelper utility class to setup a physics list for biasing in case this physics list is not of G4VModularPhysicsList type but inherits directly from
G4VUserPhysicsList.]
// Get physics list helper:
G4PhysicsListHelper* ph = G4PhysicsListHelper::GetPhysicsListHelper();
...
// Assume "particle" is a pointer on a G4ParticleDefinition object
G4String particleName = particle->GetParticleName();
if (particleName == "gamma")
{
ph->RegisterProcess(new G4PhotoElectricEffect , particle);
ph->RegisterProcess(new G4ComptonScattering ,
particle);
ph->RegisterProcess(new G4GammaConversion ,
particle);
G4ProcessManager* pmanager = particle->GetProcessManager();
G4BiasingHelper::ActivatePhysicsBiasing(pmanager, "phot");
G4BiasingHelper::ActivatePhysicsBiasing(pmanager, "compt");
G4BiasingHelper::ActivatePhysicsBiasing(pmanager, "conv");
G4BiasingHelper::ActivateNonPhysicsBiasing(pmanager);
}
\end{lstlisting}
\begin{itemize}
	\item A last way to setup the physics list is by direct insertion of the
G4BiasingProcessInterface instances, but this requires solid expertise in physics
list creation.
\end{itemize}

设置物理列表的最后一种方法是直接插入G4BiasingProcessInterface实例，但这需要物理列表创建方面的扎实专业知识。

In case you also use parallel geometries, you have to make the generic biasing
sensitive to these. Assuming you have created three parallel geometries with
names "parallelWorld1", "parallelWorld2" and "parallelWorld3" that you want to be
active for neutrons, the additional calls you have to make compared to example
\textit{EvtBias.GenericBiasing.Overview.UsePhysConstructor }above are simply:

如果您也使用平行几何，则必须使这些通用偏置敏感。
假设您已经创建了三个名称为parallelWorld1``，''parallelWorld2``和''parallelWorld3``的并行几何图形，您希望对中子有效，但与上面的示例EvtBias.GenericBiasing.Overview.UsePhysConstructor相比，您必须进行额外的调用：
\begin{lstlisting}[caption=调用激活平行几何导航]
// -- activate parallel geometries for neutrons:
biasingPhysics->AddParallelGeometry("neutron","parallelWorld1");
biasingPhysics->AddParallelGeometry("neutron","parallelWorld2");
biasingPhysics->AddParallelGeometry("neutron","parallelWorld3");
\end{lstlisting}

It is also possible, even though less convenient, to use the G4BiasingHelper
utility class making calls to the static method limiter =
G4BiasingHelper::AddLimiterProcess(pmanager,"limiterProcessName") in addition to
the ones of example \textit{EvtBias.GenericBiasing.Overview.UseBiasingHelper
}above. This call returns a pointer limiter on the constructed
G4ParallelGeometriesLimiterProcess process, setting its name as
"limiterProcessName", this pointer has then to be used to specify the parallel
geometries to the process : limiter-$>$AddParallelWorld("parallelWorld1"). . .

尽管不太方便，除了上面的示例EvtBias.GenericBiasing.Overview.UseBiasingHelper之外，还可以使用G4BiasingHelper实用程序类调用静态方法limiter
= G4BiasingHelper :: AddLimiterProcess（pmanager，``limiterProcessName''）。
这个调用在构造的G4ParallelGeometriesLimiterProcess进程上返回一个指针限制器，将其名称设置为``limiterProcessName''，然后使用该指针指定进程的并行几何：limiter-$>$
AddParallelWorld（``parallelWorld1''）
\end{enumerate}


\paragraph{Existing biasing operations, operator and interaction
laws【现有的偏差操作，操作者和交互规则】}

This is set of biasing operations and one operator available in 10.1, as well as
a set of biasing interaction laws. These are defined in
source/processes/biasing/generic. Please note that several examples
(\textit{Examples}) also implement dedicated operators and operations.

这是一组偏置操作和10.1中的一个操作符，以及一组偏置交互规则。 这些在source/processes/biasing/generic中定义。
请注意，几个例子（\textit{Examples}）也实现了专门的操作。

These classes have been tested for now with neutral particles.

现在已经用中性粒子对这些类进行了测试。

\begin{itemize}
	\item G4VBiasingOperation classes:

\begin{itemize}
	\item G4BOptnCloning: a non-physics-based biasing operation that clones the current
track. Each of the two copies is given freely a weight.

G4BOptnCloning：克隆当前体的非基于物理学的偏置操作。两个副本中的每一个都可以自由的权重。
	\item G4BOptnChangeCrossSection: a physics-based biasing operation to
change one process crosssection

G4BOptnChangeCrossSection：一种基于物理的偏置操作，用于更改一个过程横截面
	\item G4BOptnForceFreeFlight: a physics-based biasing operation to force a flight with
no interaction through the current volume. This operation is better said a
``silent flight'': the flight is conducted under a zero weight, and the track
weight is restored at the end of the free flight, taking into account the
cumulative weight change for the non-interaction flight. This special feature is
because this class in used in the MCNPlike force collision scheme
G4BOptrForceCollision.

G4BOptnForceFreeFlight：一种基于物理学的偏置操作，用于在当前volume下强制飞行而不与任何交互。这种操作更好地说是一种``静音飞行''：在零重量下进行飞行，考虑到非交互飞行的累积重量变化，在自由飞行结束时恢复track重量。这个特殊功能是因为这个类在MCNP强制碰撞方案中使用了G4BOptrForceCollision。
	\item G4BOptnForceCommonTruncatedExp: a physics-based biasing operation to force a
collision inside the current volume. It is ``common'' as several processes may be
forced together, driving the related interaction law by the sum of these
processes cross-section. The relative natural occurrence of processes is
conserved. This operation makes use of a ``truncated exponential'' law, which is
the exponential law limited to a segment [0,L], where L is the distance to exit
the current volume.

G4BOptnForceCommonTruncatedExp：基于物理学的偏置操作，强制在当前体内发生碰撞。这是``共同的''，因为可能会将多个过程强加在一起，通过这些过程的总和来推动相关的相互作用规则。过程的相对自然发生是保守的。该操作使用``截断指数''定律，该定律是限于段[0，L]的指数律，其中L是离开当前体的距离。
\end{itemize}
	\item G4VBiasingOperator class:

\begin{itemize}
	\item G4BOptrForceCollision: a biasing operator that implements a force collision
scheme quite close to the one provided by MCNP. It handles the scheme though the
following sequence:
	
	 G4BOptrForceCollision：一种偏置算子，实现与MCNP提供的强制碰撞方案非常接近。 它通过以下顺序处理该方案：

\begin{enumerate}
	\item The operator starts by using a G4BOptnCloning cloning operation, making a copy
of the primary entering the volume. The primary is given a zero weight.

操作员使用G4BOptnCloning克隆操作启动，制作进入volume的主要副本。初始的权重为零。
	\item The primary is then transported through to the volume, without interactions.
This is done with the operator requesting forced free flight
G4BOptnForceFreeFlight operations to all physics processes. The weight is zero to
prevent the primary to contribute to scores. This flight purpose is to accumulate
the probability to fly through the volume without interaction. When the primary
reaches the volume boundary, the first free flight operation restores the primary
weight to its initial weight and all operations multiply this weight by their
weight for non-interaction flight. The operator then abandons here the primary
track, letting it back to normal tracking.

初始粒子运输到volume，没有相互作用。这是通过操作员向所有物理过程请求强制自由飞行G4BOptnForceFreeFlight操作完成的。权重为零以防止主要贡献分数。这个飞行目的是为了积累在没有交互的情况下飞行通过该体的概率。当初级飞机到达航线边界时，第一次自由飞行操作将初级权重恢复到其初始权重，并且所有操作都将该权重乘以其非重叠飞行的权重。操作员然后放弃主要径迹，让它回到正常径迹。
	\item The copy of the primary track starts and the track is forced to interact in the
volume, using the G4BOptnForceCommonTruncatedExp operation, itself using the
total cross-section to compute the forced interaction law (exponential law
limited to path length in the volume). One of the physics processes is randomly
selected (on the basis of cross-section values) for the interaction.

使用G4BOptnForceCommonTruncatedExp操作，使用总横截面来计算强制相互作用规则（指数规则限于体中的路径长度），主track的副本开始并且track被迫在volume中相互作用。其中一个物理过程是随机选择的（基于横截面值）进行交互。

	\item Other processes are receiving a forced free flight operation, from the operator.
	
	其他程序正在接受来自操作员的强制自由飞行操作。
	\item The copy of the primary is transported up to its interaction point. With these
operations configured, the G4BiasingProcessInterface instances have all needed
information to automatically compute the weight of the primary track and of its
interaction products.

初始的副本被运送到其交互点。通过配置这些操作，G4BiasingProcessInterface实例具有所有需要的信息来自动计算主track及其交互产品的权重。
\end{enumerate}
As this operation starts on the volume boundary, a single force interaction
occurs: if the track survives the interaction (e.g Compton process), as it moved
apart the boundary, the operator does not consider it further.

由于该操作是在体边界上开始的，所以会发生单个力的相互作用：如果径迹在相互作用（例如康普顿过程）中存在，则当它离开边界时，操作员不会进一步考虑它。
\end{itemize}
\item G4VBiasingInteractionLaw classes. These classes describe the interaction law in
term of a noninteraction probability over a segment of length l, and an
``effective'' cross-section for an interaction at distance l (see Physics
Reference Manual, section generic biasing [to come]). An interaction law can also
be sampled.

 G4VBiasingInteractionLaw类。
这些类描述了长度为l的非交互概率的交互规律，以及距离为l的交互的``有效''横截面（参见物理参考手册，通用偏置部分[将来]）。 交互法也可以被抽样。

\begin{itemize}
	\item G4InteractionLawPhysical: the usual exponential law, driven by a cross-section
constant over a step. The effective cross-section is the cross-section.

G4InteractionLawPhysical：通常的指数法则，由一个步长的横截面常数驱动。 有效横截面是横截面。
	\item G4ILawForceFreeFlight: an ``interaction'' law for, precisely, a non-interacting
track, with noninteraction probability always 1, and zero effective
cross-section. It is a limit case of the modeling.

G4ILawForceFreeFlight：一个``相互作用''定律，正好是一个非相互作用的径迹，非交互概率总是为1，零有效截面。 这是建模的一个极限情况。
	\item G4ILawTruncatedExp: an exponential interaction law limited to a segment [0,L].
The non-interaction probability and effective cross-section depend on l, the
distance travelled, and become zero and infinite, respectively, at l=L.

G4ILawTruncatedExp：限于段[0，L]的指数相互作用法则。 非交互概率和有效横截面取决于l，行进的距离，并分别在l = L时变为零和无限。

\end{itemize}
\end{itemize}

\paragraph{Changes from 10.0 to 10.1【从10.0到10.1的改变】}

The G4VBiasingOperation class has been evolved to simplify the interface. The
changes regard physics-based biasing (occurrence biasing and final state biasing)
and are:

G4VBiasingOperation类已经发展到简化接口。 这些变化涉及基于物理的偏置（发生偏置和最终状态偏置）并且是：

\begin{itemize}
	\item Suppression of the method virtual G4ForceCondition ProposeForceCondition(const G4ForceCondition wrappedProcessCondition)
	\begin{itemize}
	\item The functionality has been kept, absorbing the ProposeForceCondition(...) method
by the ProvideOccurenceBiasingInteractionLaw(...) one, which has now the
signature:
\begin{lstlisting}
virtual const G4VBiasingInteractionLaw*
ProvideOccurenceBiasingInteractionLaw ( const
G4BiasingProcessInterface* callingProcess, G4ForceCondition&
proposeForceCondition) = 0;
\end{lstlisting}

\item The value of proposeForceCondition passed to the method is the G4ForceCondition
value of the wrapped process, as this was the case with deprecated method
ProposeForceCondition(...)
\end{itemize}
\item Suppression of the virtual method ``G4bool DenyProcessPostStepDoIt(const
G4BiasingProcessInterface* callingProcess, const G4Track* track, const G4Step*
step, G4double\& proposedTrackWeight)'':

抑制虚拟方法``G4bool DenyProcessPostStepDoIt（const G4BiasingProcessInterface *
callingProcess，const G4Track * track，const G4Step *
step，G4double＆proposedTrackWeight）''

\begin{itemize}
	\item This method was used to prevent the wrapped process hold by callingProcess to
have its PostStepDoIt(...) called, providing a weight for this non-call.

此方法用于防止通过调用进程保持包装进程的PostStepDoIt（...）调用，为此非调用提供权重。
	\item The method has been removed, but the functionality still exists, and has been
merged and generalized with the change of the pure virtual
ApplyFinalStateBiasing(...) described just after.

该方法已被删除，但功能仍然存在，并且已经与稍后描述的纯虚拟ApplyFinalStateBiasing（...）的更改合并和推广。
\end{itemize}
\item Extra argument G4bool\& forceBiasedFinalState added as last argument of virtual
G4VParticleChange* ApplyFinalStateBiasing( const G4BiasingProcessInterface*
callingProcess, const G4Track* track, const G4Step* step, G4bool\& forceBiasedFinalState) = 0

额外参数G4bool＆forceBiasedFinalState添加为虚拟G4VParticleChange的最后一个参数*
ApplyFinalStateBiasing（const G4BiasingProcessInterface * callingProcess，const
G4Track * track，const G4Step * step，G4bool＆forceBiasedFinalState）= 0

\begin{itemize}
	\item This method is meant to return a final state interaction through the
G4VParticleChange. The final state may be the analog wrapped process one, or a
biased one, which comes with its weight correction for biasing the final state.
If an occurrence biasing is also at play in the same step, the weight correction
for this biasing is applied to the final state before this one is returned to the
stepping. This is the default behavior. This behavior can be controlled by
forceBiasedFinalState:

此方法旨在通过G4VParticleChange返回最终状态交互。 最终状态可能是模拟包装过程，也可能是有偏差的过程，其偏权重是为了偏置最终状态。
如果在同一步骤中发生偏差也发挥作用，则将该偏差的权重校正应用于最终状态，然后再返回到步进。 这是默认行为。
这种行为可以通过forceBiasedFinalState来控制
 \begin{itemize}
	\item If forceBiasedFinalState is left false, the above default behavior is applied.
	
	如果forceBiasedFinalState为false，则应用上述默认行为。
	\item If forceBiasedFinalState is set to true, the G4VParticleChange final state will
be \textit{returned as is }to the stepping, and that, \textit{regardless }there
is an occurrence at play. Hence, when setting forceBiasedFinalState to true, the
biasing operation \textit{takes full responsibility }for the total weight
(occurrence + final state) calculation.

如果forceBiasedFinalState设置为true，那么G4VParticleChange
final状态将按照原样返回到步进中，并且无论发生什么事件。

因此，在将forceBiasedFinalState设置为true时，偏置操作将对总权重（出现+最终状态）计算承担全部责任。
\end{itemize}


\end{itemize}
\item Deletion of G4ILawCommonTruncatedExp, which could be eliminated after better
implementation of G4BOptnForceCommonTruncatedExp operation.

删除G4ILawCommonTruncatedExp，在更好地实施G4BOptnForceCommonTruncatedExp操作后可以将其删除。
\end{itemize}

\paragraph{Changes from 10.1 to 10.2【从10.1到10.2的改变】}

Changes in 10.2 derive from the introduction of the track feature
G4VAuxiliaryTrackInformation. They regard essentially the force collision
operator G4BOptrForceCollision and related features. These changes are
transparent to the user if using G4BOptrForceCollision and following
examples/extended/biasing/ GB02. The information below are provided for
developers of biasing classes.

The G4VAuxiliaryTrackInformation functionality allows to extend the G4Track
attributes with an instance of a concrete class deriving from
G4VAuxiliaryTrackInformation. Such an object is registered to the G4Track using
an ID that has to be previously obtained from the G4PhysicsModelCatalog. The
G4VBiasingOperator class defines two new virtual methods, Configure() and
ConfigureForWorker(), to help with the creation of these ID's at the proper time
(see G4BOptrForceCollision as an example).

Before 10.2, the G4BOptrForceCollision class was using state variables to make
the bookkeeping of the tracks handled by the scheme. Now this bookkeeping is
handled using a G4VAuxiliaryTrackInformation, G4BOptrForceCollisionTrackData.

To help with the bookkeeping, the base class G4VBiasingOperator was defining a set of methods
(GetBirthOperation(..), RememberSecondaries(..), ForgetTrack(..)), these have been re-
moved in 10.2 and are easy to overpass with a dedicated G4VAuxiliaryTrackInformation.

10.2的变化来自径迹特征G4VAuxiliaryTrackInformation的引入。他们基本上认为强制碰撞算子G4BOptrForceCollision和相关特征。如果使用G4BOptrForceCollision和以下examples/extended/biasing/ GB02，则这些更改对用户是透明的。以下信息是为偏置类的开发者提供的。

G4VAuxiliaryTrackInformation功能允许使用派生自G4VAuxiliaryTrackInformation的具体类的实例来扩展G4Track属性。使用必须事先从G4PhysicsModelCatalog获得的ID将这样的对象注册到G4Track。

G4VBiasingOperator类定义了两个新的虚拟方法Configure（）和ConfigureForWorker（），以帮助在适当的时候创建这些ID（请参阅G4BOptrForceCollision作为示例）。

在10.2之前，G4BOptrForceCollision类使用状态变量来为计划处理的径迹记帐。现在，使用G4VAuxiliaryTrackInformation，G4BOptrForceCollisionTrackData处理此簿记。

为了帮助簿记，基类G4VBiasingOperator定义了一组方法（GetBirthOperation（..），RememberSecondaries（..），ForgetTrack（..）），这些在10.2中已被删除，并且很容易被专用的G4VAuxiliaryTrackInformation超越。